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
})
[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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With