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" ????? } 
6
  • 4
    You've copied the examples from MDN, 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. Commented Feb 2, 2016 at 8:47
  • And there is a a property called "foo" with a value "hello". Why doesn't it show it? Commented Feb 2, 2016 at 8:48
  • @Tushar Did you try the code? "Hello" is indeed not printed. Commented Feb 2, 2016 at 8:50
  • Yes, and my question is Why? Isn't foo the fourth element of arr? Commented Feb 2, 2016 at 8:51
  • 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. Commented Feb 2, 2016 at 8:52

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.