3

This is in Chromium 78:

for (var i in [1,3,5]) console.log(i+1)

enter image description here

Now, I expected for (var i in [1,3,5]) console.log(i+1) to output 1, 2, 3, because i should be an index value. I know the MDN docs mention that the order may come out strangely in this case, but why the type conversion?

14
  • 2
    for...in returns a string key. Also: Why is using “for…in” with array iteration a bad idea? Commented Nov 13, 2019 at 13:37
  • 1
    Checkout the "Array iteration and for...in" section of the manual, you referenced. There is the explanation. Commented Nov 13, 2019 at 13:40
  • 2
    Also see note section for...in should not be used to iterate over an Array where the index order is important" Commented Nov 13, 2019 at 13:40
  • 1
    That's because an array is really just a special type of object and object keys are always strings. Commented Nov 13, 2019 at 13:43
  • 2
    The much harsher problem with for ... in is, that unlike many other methods (e.g. Object.keys), it iterates the prototype chain aswell. Therefore, e.g. Array.prototype["surprise!"] = 1; for (let p in []) console.log(p); may be "surprise!"'ing. Commented Nov 13, 2019 at 13:55

1 Answer 1

5

i is not the index, i is the property key of the array object. Property keys are always strings.

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.