A forin loop is used to iterate over an object or an array. A javascript object consists of a collection of key-value pairs enclosed between curly braces. Example of an object is:

person = {
   name: 'John',
   age: 30
}

 More details about a javascript object can be found here

Though this loop is not recommended for iterating over an array but it can be used.
Syntax
A forin loop can be used with the following syntax.

for(let key in object) {
// loop statements
}

where key is a user defined variable. In every iteration, this variable contains a key of an object.
Example
A forin loop is used for iterating over an object. In every iteration, it prints the key of object and its corresponding value. Value of an object key can be retrieved by enclosing the key in square brackets preceded by the name of object.
Example of its usage is given below.

person = {
   name: 'John',
   age: 30
}
for(let key in person) {
  console.log('Key is: ' + key);
  console.log('Value is: ' + person[key]);
}

Output of above loop is

Key is: name
Value is: John
Key is: age
Value is: 30

Leave a Reply