The for in loop is used to list all properties of a given object in JavaScript.

It can be used on objects but also on arrays. Using this loop it is not necessary to specify the length of the array as we did using the for loop instead.

Warning: do not use the for in loop on arrays when the order of the index is important, in this case it is necessary to prefer the simple for loop. Thus, we can say that the for in loop is more used with objects in JavaScript.

The syntax is as follows:

for (var in object)
  instructions

Where in is a keyword used to test whether the specified variable is present in the object. So the expression (var in object) returns a Boolean value. As long as this value is true the cycle will be executed.

Let’s take some examples to better understand how it works.

Example 1 – for in loop JavaScript

In this first example we are building a simple user object with 3 properties.


user = {
  name: 'Coding',
  lastname: 'Creativo',
  phone: '333'
}

for (var k in user){
  console.log(k);
}

In our example k will take the value of all the properties present in our object. So in the console.log you will see: name, surname and telephone.

Instead of k we can indicate any variable name. The name is purely indicative. Also pay attention to the fact that var.

The for in loop in JavaScript is therefore executed until it finds properties within the object.

If we want to display the property values ​​as well, then we need to indicate each element.

In this case we use the notation with square brackets, this is because if I wrote user.k, k is not recognized as a property of the user object, so it would give an error. So the only way to access the key value in an object is the notation with square brackets.


user = {
  name: 'Coding',
  lastname: 'Creativo',
  phone: '333'
}

for (var k in user){
  console.log(k + 'value ' + user[k]);
}

In the console in this way I will see: name value Coding, last name value Creative and telephone value 333.

Banner pubblicitario

If we find ourselves using nested objects, we can nest the for loop inside another, as shown in the example below:


user = {
  name: 'Coding',
  lastname: 'Creativo',
  phone: '333',
  address: {
    street: 'dei tulipani',
    city: 'Modica'
  }
}

for (var k in user){
  if (k == 'address'){
    for (var j in user.address){
      console.log(j + ': ' + user.address[j]);
    }
  } else {
      console.log(k + ': ' + user[k]);
  }
}

So to view the elements within the address property, which represents an object, I use another for loop.

We note that we can also write in this way:


for (var k in user){
  if (k == 'address'){
    for (var j in user[k]){
      console.log(j + ': ' + user[k][j]);
    }
  } else {
      console.log(k + ': ' + user[k]);
  }
}

In this lesson we have introduced this new iterative cycle, the for in loop in JavaScript, in the next lessons I will propose other examples.

Alcuni link utili

Indice tutorial JavaScript