The for each..in
statement iterates a specified variable over all values of an object's properties. For each distinct property, a specified statement is executed. This was introduced by Mozilla in JavaScript 1.6 (see comment by @CMS below), and is not supported in all mainstream browsers.
For each example:
var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
for each (var item in obj) {
sum += item;
}
console.log(sum); // prints "26", which is 5 + 13 + 8
A similar statement is for..in
, which iterates over the property names instead of property values. The same example written using for..in
:
var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
for (var prop in obj) {
sum += obj[prop];
}
console.log(sum); // prints "26", which is 5 + 13 + 8
The for..in
statement has been around since JavaScript 1.0, so you're safe to use it in all browsers.
These statements are different from the traditional for
loop, since they are used to iterate over the properties of an object. A for
loop can be used to iterate over the elements of an array, but it cannot be used to iterate over the properties of an object, unless you can use ECMAScript 5's Object.keys
, which could be used to implement the above example as follows:
var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};
var keys = Object.keys(obj)
for (var i = 0; i < keys.length; i++) {
sum += obj[keys[i]];
}
console.log(sum); // prints "26", which is 5 + 13 + 8
As for the with
statement, note the following:
JavaScript looks up an unqualified name by searching a scope chain associated with the execution context of the script or function containing that unqualified name. The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property. Otherwise a 'ReferenceError' is thrown.
Therefore, consider the following:
var prop1 = 10;
var obj = {prop1: 5, prop2: 13, prop3: 8};
with (obj) {
console.log(prop1); // prints 5 instead of 10
}
Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.