for-in statement

The for-in construct creates a loop to iterate over an object.

Syntax

javascriptfor (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:

javascriptlet 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:

javascriptlet obj = {a: 1, b: 2, c: 3};

for (let key in obj) {
  console.log(obj[key]); // shows 1, 2, 3
}

See also