Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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
})
like image 833
KMA Badshah Avatar asked Mar 19 '26 11:03

KMA Badshah


1 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

like image 64
hgb123 Avatar answered Mar 21 '26 02:03

hgb123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!