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

Ramin Omrani
  • 3,673
  • 8
  • 34
  • 60

1 Answers1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • so you mean foo is a property, not an element. but aren't array indexes, properties themselves? – Ramin Omrani Jun 27 '15 at 17:34
  • 1
    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. –  Jun 27 '15 at 17:39