1

In the NodeJs console, using a non-strict comparison of an empty object to true or false I always get false. Why?

> ({}) == true || ({}) == false
false
0

1 Answer 1

4

Because you're comparing an object to a boolean. That's where things get complicated as you're not using a type-safe comparison.

Booleans get compared to other types as if they were numbers, i.e. true is casted to 1 first and false to 0. Then, when an object is compared to a number, it will be casted to a primitive value (without a preferred type) - invoking the DefaultValue algorithm. On plain objects, this will stringify them, and your empty object {} becomes "[object Object]", which is neither equal to 0 nor 1.

There are some objects however that will compare as equal to booleans, for example:

[0] == false
[1] == true
({toString:function(){return "1"}}) == true
({valueOf:function(){return 0}}) == false
({valueOf:function(){return true}}) == true
Sign up to request clarification or add additional context in comments.

4 Comments

To be precise, [object Object] will be cast to Number as well (when compared with booleans), becoming NaN in process. And NaN is obviously incomparable to anything. ) A short rule of thumb: when in doubt, add Strings, compare Numbers. Still, it's better never use == when comparing objects and primitives.
@raina77ow: Yes, depending on what value the DefaultValue operation (i.e. the object's toString/valueOf methods) yields. If that is a string or boolean, it will be parsed to a number to be comparable with 0 or 1.
Great explanation. Does this strike anyone else as a problem with JS or am I missing something? Should one !! objects before doing such comparisons? Thanks all.
No, it's not a problem with JS, it's a problem with abuse of it's dynamic type system. One should not never need to compare an object with a boolean. What are you attempting to do anyway?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.