What is the difference between ( for... in ) and ( for... of ) statements in JavaScript?

Mukund Kumar picture Mukund Kumar · Mar 26, 2015 · Viewed 205.4k times · Source

I know what is for... in loop (it iterates over key), but heard the first time about for... of (it iterates over value).

I am confused with for... of loop. I didn't get adject. This is the code below :

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 is does not log "3", "5", "7", "hello"
}

What I got is, for... of iterates over property values. Then why it doesn't log (return) "3", "5", "7", "hello" instead of "3", "5", "7"? but for... in loop iterates over each key ("0", "1", "2", "foo"). Here for... in loop also iterates over foo key. But for... of does not iterate over the value of foo property i.e "hello". Why it is like that?

Long story in short:

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

Example Link

Answer

Bergi picture Bergi · Mar 26, 2015

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).