9

Why does {} == false evaluate to false while [] == false evaluates to true in javascript?

prateekj_ahead
  • 167
  • 1
  • 1
  • 13

1 Answers1

7

This is the type conversion that takes place according to the Abstract Equality Comparison Algorithm:

{} == false                // step 7 {} == ToNumber(false)
{} == 0                    // step 9 ToPrimitve({}) == 0
"[object Object]" == 0     // step 5 ToNumber("[object Object]") == 0
NaN == 0                   // step 1.c.i

[] == false                // step 7 [] == ToNumber(false)
[] == 0                    // step 9 ToPrimitve([]) == 0
"" == 0                    // step 5 ToNumber("") == 0
0 == 0                     // step 1.c.iii

References: ToNumber, ToPrimitive

And because of this, prefer to use strict comparison.


Some examples how ToPrimitive converts objects to primitives during comparison. By default, the valueOf method of the object will be called, and then toString if valueOf doesn't return a primitive value. For Date objects it will call toString by default.

var obj = {};
obj.valueOf();        // Object { } // the object itself
obj.toString();       // "[object Object]"


obj.valueOf = function() { return 123; };
obj == 123; // true

obj.toString = function() { return 'foo bar'; };
obj == 123; // false
obj == 'foo bar'; // true

// Date object

var date = new Date();
date.valueOf();        // 1421430720379
date.toString();       // "Fri Jan 16 2015 09:52:00 GMT-0800 (PST)"

date == 1421430720379 // false
date == "Fri Jan 16 2015 09:52:00 GMT-0800 (PST)" // true

date.toString = function() { return 'foo'; };
date == 'foo'; // true
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Does this mean that the primitives of all objects are strings? @FelixKling Btw, thanks for such a clear answer! :) – prateekj_ahead Jan 16 '15 at 17:35
  • 1
    It's a bit more complicated than that. ToPrimitive accepts a hint which should indicate whether the object should be converted to a number or string. If no hint is provided, the default is "string" for Date objects and "number" for all other objects. In case of "number", the `valueOf` method of that object is called. **However** if that method does *not return* a primitive value, it falls back to `toString`. And by default, `valueOf` simply returns the object itself, so it's not a primitive. – Felix Kling Jan 16 '15 at 17:45
  • Added some examples how objects are converted to primitives. – Felix Kling Jan 16 '15 at 17:55