80
5.5.4 for/in
The
for/in
statement uses the
for
keyword, but it is a completely different kind of loop
than the regular
for
loop. A
for/in
loop looks like this:
for (variable in object)
statement
variable
typically names a variable, but it may be any expression that evaluates to an
lvalue (§4.7.3) or a
var
statement that declares a single variable—it must be something
suitable as the left side of an assignment expression.
object
is an expression that eval-
uates to an object. As usual,
statement
is the statement or statement block that serves
as the body of the loop.
It is easy to use a regular
for
loop to iterate through the elements of an array:
for(var i = 0; i < a.length; i++) // Assign array indexes to variable i
console.log(a[i]); // Print the value of each array element
The
for/in
loop makes it easy to do the same for the properties of an object:
for(var p in o) // Assign property names of o to variable p
console.log(o[p]); // Print the value of each property
To execute a
for/in
statement, the JavaScript interpreter first evaluates the
object
ex-
pression. If it evaluates to
null
or
undefined
, the interpreter skips the loop and moves
on to the next statement.
3
If the expression evaluates to a primitive value, that value is
converted to its equivalent wrapper object (§3.6). Otherwise, the expression is already
an object. The interpreter now executes the body of the loop once for each enumerable
property of the object. Before each iteration, however, the interpreter evaluates the
variable
expression and assigns the name of the property (a string value) to it.
Note that the
variable
in the
for/in
loop may be an arbitrary expression, as long as it
evaluates to something suitable for the left side of an assignment. This expression is
evaluated each time through the loop, which means that it may evaluate differently
each time. For example, you can use code like the following to copy the names of all
object properties into an array:
var o = {x:1, y:2, z:3};
var a = [], i = 0;
for(a[i++] in o) /* empty */;
JavaScript arrays are simply a specialized kind of object and array indexes are object
properties that can be enumerated with a
for/in
loop. For example, following the code
above with this line enumerates the array indexes 0, 1, and 2:
for(i in a) console.log(i);
The
for/in
loop does not actually enumerate all properties of an object, only the enu-
merable properties (see §6.7). The various built-in methods defined by core JavaScript
are not enumerable. All objects have a
toString()
method, for example, but the
3. ECMAScript 3 implementations may instead throw a TypeError in this case.
100 | Chapter 5: Statements