Array index does not respond to strict equality when using for...in loop

Viewed 84

This is a strange behavior that I've encountered today. But I cannot understand why it happens.

for (let x in [1]) {
    console.log(x === 0) // false
    console.log(x == 0) // true
}

The code snippet should be self explanatory. On the first log we have strict equality and on the next one we have loose equality. Why are they returning different results? Aren't numbers of the same value equal no matter how we're comparing them?

P.S: This problem doesn't exist if you're using array functions such as forEach() and map() for iteration

[1].forEach((_, i) => {
    console.log(i === 0) // true
    console.log(i == 0) // true
})
2 Answers

[1] is equivalent to {0: 1}

When you use for..in, it iterates through object's properties (keys). While keys are all in string, so it iterates through ['0']

So

'0' === 0 // false
'0' == 0 // true

could be easily understand since then

In this case, x is not a number because for ... in iterates over object keys:

for (let x in [1]) {
    console.log(typeof x);
    console.log(x === 0) // false
    console.log(x == 0) // true
}

For arrays, you should be using for ... of:

for (let x of [1]) {
    console.log(typeof x);
    console.log(x === 0) // false
    console.log(x == 0) // false
}

Related