Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}
like image 489
Xuzheng Wang Avatar asked Oct 08 '15 11:10

Xuzheng Wang


People also ask

What is the use of for of loop?

A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.

Can we break for of loop in JavaScript?

A for..in loop can't use break. It's not possible to end it in this way.

What is for in loop and for of loop in JavaScript?

JavaScript supports different kinds of loops: for - loops through a block of code a number of times. for/in - loops through the properties of an object. for/of - loops through the values of an iterable object.


1 Answers

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.

like image 99
Touffy Avatar answered Sep 20 '22 07:09

Touffy