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"
}
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.
A for..in loop can't use break. It's not possible to end it in this way.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With