Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the "in" operator work with non-string keys?

When I use in operator in javascript, I find something strange. It seems that in uses a similar rule as == but not the same. Here are some tests:

var obj = {1: 'a', 3: 'b'};
1 in obj     //=> true
'1' in obj   //=> true
[1] in obj   //=> true
true in obj  //=> false

Because 1 == '1' == [1] == true, so it seems that operand will be cast to string or integer type before comparison with in operator except for boolean. So I wonder am I right?

like image 514
foolyoghurt Avatar asked May 18 '26 14:05

foolyoghurt


1 Answers

You're correct. It will first convert the left operand to a string, note however that the rules for converting between various data types in JavaScript are a lot more subtle than you might think.

true == "true"   //=> true
true == "1"      //=> true
"true" == "1"    //=> false

The precise rules are fairly complicated*, but the important thing to remember here is that when a Boolean is converted directly to a string, this is the result:

true.toString()  //=> "true"
false.toString() //=> "false"

So this is exactly the behavior you should expect, for example:

var obj = { "true": "a", "false": "b" };
true in obj      //=> true
false in obj     //=> true
1 in obj         //=> false

* See Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?

like image 152
p.s.w.g Avatar answered May 20 '26 02:05

p.s.w.g



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!