Although I am familiar with the for... in
loop (which iterates over keys), I recently came across the for... of
loop for the first time, which apparently iterates over values.
I find myself confused by this for... of
loop.
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 doesn't log "3", "5", "7", "hello"
}
My understanding is that for... of
should iterate over property values. So why does it only log
"3", "5", "7"
instead of "3", "5", "7", "hello"
?
Unlike the for... in
loop, which goes through each key (
"0", "1", "2", "foo"
) including the foo
key, the for... of
loop specifically excludes the value of the foo
property, "hello"
. But why is that?
While testing the code using the for... of
loop, I expected it to log
"3", "5", "7", "hello"
, but it only displayed "3", "5", "7"
. What could be the reason behind this behavior?