0

I am looking at a sample from mozilla documents about JS and here is this snippet that shows that For..of prints 3, 5, 7, but why not "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" ?????
}
v.g.
  • 1,018
  • 4
  • 19
  • 33
  • 4
    You've copied the examples from [MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of#Difference_between_for...of_and_for...in), however you didn't read what it says, _While `for...in` iterates over property names, `for...of` iterates over property values:_. `hello` is the **value** of the key `foo`. – Tushar Feb 02 '16 at 08:47
  • And there is a a property called "foo" with a value "hello". Why doesn't it show it? – v.g. Feb 02 '16 at 08:48
  • @Tushar Did you try the code? "Hello" is indeed not printed. – Lewis Feb 02 '16 at 08:50
  • Yes, and my question is Why? Isn't foo the fourth element of arr? – v.g. Feb 02 '16 at 08:51
  • BTW, MDN is not always correct. It's better to try the sample code then see the ouput. – Lewis Feb 02 '16 at 08:52
  • 1
    @v.g.: No. `arr[3]` is undefined. `arr.foo` is just an arbitrary property of the array, like `arr.length` is, it's not an array element. Only integer-indexed properties are. – Bergi Feb 02 '16 at 08:52

1 Answers1

0

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

See this.

Source.

EDIT:
foo is property. 3, for example, is an element but "hello" isn't. Elements are the values that occur as values of integer-valued properties.

Community
  • 1
  • 1
PRVS
  • 1,502
  • 4
  • 28
  • 65