for-in statement
The for-in construct creates
a loop to iterate over an object.
Syntax
for (let variableForKey in object) {
/*
The iterated object keys will fall
into the variableForKey one by one.
*/
};
Example
Let's iterate over the object keys and display them on the screen:
let obj = {a: 1, b: 2, c: 3};
for (let key in obj) {
console.log(key); // shows 'a', 'b', 'c'
}
Example
And now we will display the object elements:
let obj = {a: 1, b: 2, c: 3};
for (let key in obj) {
console.log(obj[key]); // shows 1, 2, 3
}
See also
-
the lesson from JavaScript tutorial
detailing how to work with thefor-inloop -
the
for-ofstatement
that creates a loop to iterate over an array -
the
breakstatement
that breaks a loop -
the
continuestatement
that moves a loop to next iteration