7

In the MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of,

It says While for...in iterates over property names, for...of iterates over property values.

Then, why does the second for...of not log "hello"?

let arr = [3, 5, 7];
arr.foo = "hello";

for (let i in arr) {
   console.log(i); // logs "0", "1", "2", "foo"
}

for (let i of arr) {
   console.log(i); // logs "3", "5", "7"
}
3
  • 4
    Iteration over arrays (using forEach, for..of) only covers their properties (even if undefined) between zero and length-1. for..in is different and iterates over enumerable properties of anything. Commented Oct 8, 2015 at 11:33
  • Thank you very much for your prompt response. Now, I don't know how to accept your answer :-) Commented Oct 8, 2015 at 11:41
  • Sorry, writing something a bit more detailed, give me a few minutes :) Commented Oct 8, 2015 at 11:41

1 Answer 1

9

The for...in statement iterates over the enumerable properties of an object, in arbitrary order.

To be more precise, that includes enumerable properties in its prototype chain as well.

And every object is treated the same. It's simple, it's confusing, lots of people hated it when it was used on arrays.

for..of uses a Symbol internally. Any object with the [Symbol.iterator] can be iterated over by for..of, but what is iterated over and in what order is defined in the Symbol, rather than by the semantics of the statement itself (allowing lazy iterators where the properties are not known initially).

In the case of arrays, the iterator goes through every property between zero and the array's length-1, even properties that are undefined and would not be picked up by for..in. But it totally ignores other properties, the same way that Array.toString() does since the beginning of time, and also Array.forEach() and its friends from ES5. That makes array iteration consistent.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much for your answer, I hope others who have encountered the same issue could benefit from this :-)
As a matter of fact this is the second for..in array-related answer I write today. Arrays are meant for numbered, ordered values.
That is true, arr.foo = "hello" should be used as key-value pair in a object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.