Maria: Won’t break terminate the program altogether?
Professor: No, it won’t, because break terminates only the innermost loop in which
it is placed. If that loop is nested within another loop, then the outer loop w ill continue
its execution as though nothing h appened.
Notice how I produced an infinite loop by simply putting the constant value true
in place of the loop condition. Since true always evaluates to true , th e loop can
only be stopped by means of break. By the way, instead of while (t rue) you will
sometimes also see for (;;) which also makes up an infinite loop.
Mike: I suspect that this program can be made shorter, without break, without
number, and using a do/while loop instead of the while loop.
Professor: You know, I think you’re r ight. I was planning to revisit the example later
today anyhow and we may just a s well tr y to make it shorter using your suggestions.
Speaking of break, there ’s a similar statemen t called continue. The difference is
that continue does not terminate the loop execution completely. It only terminates
the current iteration a nd jumps directly to the loop condition, which is then tested for
the next iteration.
Even though br eak and con tinue can some times make for elegant solutions, you
should limit yourselves to using them exclusively at the start or e nd of the loop body,
only as additional or alternative checks. Otherwise you may later overlook them,
getting yourself in some nasty trouble.
Maria: The drawn numbers produced by your cod e aren’t sorted.
Professor: Of course they aren’t becau se we haven’t implemented any sorting yet.
But we’ll be coming to it sh ortly.
9.4 Array Methods
Professor: Now, you alre ady know that a JavaScript array has a single length prop-
erty, which is automatically updated to always be one larger than the hig hest index of
the array. While array elements are a lso properties, they are usually optimized f or a
significantly faster access th an ordinary properties. There ar e three different construc-
tors for the Array object, but they can be replaced by array liter als, and we decided
to use them as they are shorter and there’s no danger of accidentally calling a wron g
constructo r if you use a single numeric argument.
There is more to arrays, though. You’ll discover that the Array objec t implements
quite a few array-manipulating methods. Two of them we are going to meet now and
you’ll find more in the JavaScript reference in section E.3 on page 374. Even what
you find there is just a selection of what this object has in store for the programmer.
For our lucky lottery number generator we ar e going to use two methods, sort() and
indexOf(). The first one is kind of self-expla natory—it simply sorts the array ele-
ments. The elements are reordered in pla ce, which means that no new array is created.
The elements of the array on which you call the sort() metho d are rearranged.
178 Meeting 9. Understanding Arrays and Strings