Search code examples
javascriptarraysfor-loopobject

Difference between ( for... in ) and ( for... of ) statements?


I know what is a for... in loop (it iterates over the keys), but I have heard about for... of for the first time (it iterates over values).

I am confused about for... of loop.

var arr = [3, 5, 7];
arr.foo = "hello";
    
for (var i in arr) {
  console.log(i); // logs "0", "1", "2", "foo"
}
    
for (var i of arr) {
  console.log(i); // logs "3", "5", "7"
  // it doesn't log "3", "5", "7", "hello"
}

I understand that for... of iterates over property values. Then why doesn't it log "3", "5", "7", "hello" instead of "3", "5", "7"?

Unlike for... in loop, which iterates over each key ("0", "1", "2", "foo") and also iterates over the foo key, the for... of does not iterate over the value of foo property, i.e., "hello". Why it is like that?

Here I console for... of loop. It should log "3", "5", "7","hello" but it logs "3", "5", "7". Why?

Example Link


Solution

  • for in loops over enumerable property names of an object.

    for of (new in ES6) does use an object-specific iterator and loops over the values generated by that.

    In your example, the array iterator does yield all the values in the array (ignoring non-index properties).