JavaScript : For In

In JavaScript, the for...in loop is used to iterate over the enumerable properties of an object. It's particularly useful for iterating over the keys of an object or the indices of an array. Here's the syntax of the for...in loop:

Syntax:


for (variable in object) {
  // Code block to be executed
}

  • variable: A variable that represents the key or index of each property or element in the object.
  • object: The object whose properties or elements are being iterated over.

Example with Object:


const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

for (let key in person) {
  console.log(key + ': ' + person[key]);
}

 

Output:


name: John
age: 30
city: New York

 

Example with Array:


const colors = ['red', 'green', 'blue'];

for (let index in colors) {
  console.log(index + ': ' + colors[index]);
}

 

Output:


0: red
1: green
2: blue
 

Notes:

 

  • The for...in loop iterates over all enumerable properties of an object, including inherited properties from the prototype chain. To iterate only over an object's own properties, you can use the hasOwnProperty() method within the loop.
  • When iterating over arrays with for...in , the loop iterates over the indices of the array, but it's generally recommended to use a for...of loop or array methods like forEach() for iterating over arrays.


const colors = ['red', 'green', 'blue'];

for (let index in colors) {
  console.log(index); // Output: 0, 1, 2
}

for (let color of colors) {
  console.log(color); // Output: red, green, blue
}

 

The for...in loop provides a convenient way to iterate over the properties of an object or the indices of an array, making it useful for various tasks in JavaScript programming. However, it's essential to be cautious when using it with objects to avoid unexpected behavior due to inherited properties.