property name is th at access to array e le ments is mostly significantly faster than access
to regular object properties. That’s due to the fact that Java Script impleme ntations
typically op timize array s fo r index access.
The second difference is that when you use a numeric index to add a new elem ent, the
length property of an array is automatically updated for you.
Maria: You said before that array s were dynamic in the sense that you could add or
remove elements. You showed us that an element is added automatically by simply
giving a value to a non-existent element. But how do you remove elements?
Professor: One way of doing that is to explicitly change the value of the length
property, which will automatically truncate or grow the size of the arra y. If you make
length smaller, then you effectively delete e le ments from the end of an array.
There also exist certain array methods like, for example, pop() and push(), which
you can use to explicitly ad d or remove ele ments.
I will now show you the for loop, which is commonly used in connection with a rrays.
9.3 for Loop
Professor: The for statement is a looping instrument similar to the while loop but
it is often more convenient when the code has to do with counting of some kind.
Counting consists of three elementary tasks: first, setting a counter to an initial value,
second, deciding when to stop, and third, deciding upon the size of the increment
(or d ecrement f or countdown). A variable used as a c ounter in a for loop is first
initialized and then tested before each iteration of the loop is executed. At th e end
of each iteration the co unter is increm ented or other w ise updated. All thr ee central
operations upon a counting variable, the initialization, the test, and the update, are
neatly grouped inside the parentheses at the beginning of the fo r loop. This is the
loop’s syntax:
for (initialize ; test ; update ) do_something
The expr essions initialize , test , and update are responsib le for manipulating a
counter variable, and do_something is a statement that represents the lo op body.
I thought it best to explain how the for loop works in a two-stage example of printing
the 10 times multiplication table. In the first stage we simply fix one of the multipli-
cands to, say, three, and print a single row of the table:
var x = 3, y;
document.write("<table border="1">");
document.write("<tr>");
for (y = 1; y <= 10; y++) {
//Prints numbers 3, 6, 9, 12, ..., 30 in one table row.
document.write("<td>" + x * y + "</td>");
}
9.3. f or Loop 173