3

I have a snippet which I'm experimenting the for...of statement on it:

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

My Question is that for...of should run on iterable values, right? so why the second for doesn't print "hello"?

1 Answer 1

5

Arrays are iterables over their elements. That's how it's defined. That is how Array[Symbol.iterator] is implemented.

See http://www.2ality.com/2015/02/es6-iteration.html.

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

2 Comments

so you mean foo is a property, not an element. but aren't array indexes, properties themselves?
0 and foo are both properties, while 3 is an element but hello is not. Elements are the values that occur as values of integer-valued properties.

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.