for each...in

Introduced in JavaScript 1.6

Summary

Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.

Note: for each...in is part of the ECMA-357 (E4X) standard, which is not widely supported by non-Mozilla browsers, not part of the ECMAScript standard.

Statement
Implemented in: JavaScript 1.6
ECMAScript Version: none

Syntax

for each (variable in object) {
  statement
}

Parameters

variable
Variable to iterate over property values, optionally declared with the var keyword. This variable is local to the function, not to the loop.
object
Object for which the properties are iterated.
statement
A statement to execute for each property. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements.

Description

Some built-in properties are not iterated over. These include all built-in methods of objects, e.g. String's indexOf method. However, all user-defined properties are iterated over.

Examples

Example: Using for each...in

Warning: Never use a loop like this on arrays. Only use it on objects. Details.

The following snippet iterates over an object's properties, calculating their sum:

var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8};

for each (var item in obj) {
  sum += item;
}

print(sum); // prints "26", which is 5+13+8

See also

Tags (1)

Contributors to this page: evilpie, Sheppy, Scipion, Elchi3, Dikrib, ethertank, Nickolay, Brettz9, ziyunfei, Ruakh, Waldo, Mgjbot, Potappo, Inimino, Afcn007, Juamei, Bzbarsky
Last updated by: ethertank,
Last reviewed by: ethertank,