JavaScript For In


The For In Loop

The JavaScript code for in helps go through the properties of an object.

Syntax

for (key in object) {
  // code block to be executed
}

Example Explained

  • The for in loop iterates over a person object
  • Each iteration returns a key (x)
  • The key is used to access the value of the key
  • The value of the key is person[x]

For In Over Arrays

The JavaScript for in statement can be used to iterate through the properties of an Array.

Syntax

for (variable in array) {
  code
}

Avoid using a loop called for in with Arrays when the sequence of the index matters.

The order in which items appear in an array depends on how it's set up, and you might not be able to find items in the array in the order you think they should be.

Using a for loop, a for of loop, or Array.forEach() is best when the order matters.


Array.forEach()

The forEach() method runs a callback function for every element in an array.

Note that the function takes 3 arguments:

  • The item value
  • The item index
  • The array itself

The given code utilizes the value parameter exclusively. It can be rephrased as follows: