Xuzheng Wang
Xuzheng Wang

Reputation: 531

JavaScript for ... of loop

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"
}

Upvotes: 7

Views: 279

Answers (1)

Touffy
Touffy

Reputation: 6561

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.

Upvotes: 9

Related Questions