What is the difference between these 2 for loops: for( x in arr) and for(x of arr)?

can anyone tell me please?

Hi @iamcris

One difference is that for...in will loop over the object and any object in it’s prototype chain.

So for example:

var test = ['hey']

for (var val in test) {
  console.log(val)
}

This would log the keys in test and all the keys on the Object prototype (as all objects, arrays are objects, automatically ‘inherit’ from the Object prototype).

for...of however, loops over any iterable objects (arrays, maps, sets etc…) providing their value to the loop variable, rather than the key. It will also NOT go up the prototype chain so in the example above, you’d get one hey logged to the console.

If you need to loop over an array, use for...of, if you need to loop over an Object use for...in and put in a check for Object.prototype.hasOwnProperty, unless you want to check the prototype chain, although that’s unlikely:

for (var key in object) {
  if (object.hasOwnProperty(key)) {
    // do work on the object
  }
}

For further reading:


1 Like

awesome!

thanks @joesmith100

1 Like