Abstract equality, inequality, and type conversion

suggest change

The Problem

The abstract equality and inequality operators (== and !=) convert their operands if the operand types do not match. This type coercion is a common source of confusion about the results of these operators, in particular, these operators aren’t always transitive as one would expect.

"" ==  0;     // true A
 0 == "0";    // true A
"" == "0";    // false B
false == 0;   // true
false == "0"; // true

"" !=  0;     // false A
 0 != "0";    // false A
"" != "0";    // true B
false != 0;   // false
false != "0"; // false

The results start to make sense if you consider how JavaScript converts empty strings to numbers.

Number("");    // 0
Number("0");   // 0
Number(false); // 0

The Solution

In case B, both operands are strings ("" and "0"), so there is no type conversion. Because "" and "0" are not the same value, "" == "0" is false, as expected.

One way to avoid the surprise is to compare operands of the same type. For a numerical comparison, convert explicitly:

const test = (a,b) => Number(a) == Number(b);
test("", 0);        // true;
test("0", 0);       // true
test("", "0");      // true;
test("abc", "abc"); // false as operands are not numbers

Or, if you want string comparison:

const test = (a,b) => String(a) == String(b);
test("", 0);   // false;
test("0", 0);  // true
test("", "0"); // false;

Side note: Number("0") and new Number("0") aren’t the same thing. The former converts to a number; the latter creates an object. Objects are compared by reference, not by value, which explains the results below.

Number("0") == Number("0");         // true;
new Number("0") == new Number("0"); // false

Finally, you have the option to use strict equality and inequality operators which will not perform any implicit type conversions.

"" ===  0;  // false
 0 === "0"; // false
"" === "0"; // false

Further reference to this topic can be found here:

Which equals operator (== vs ===) should be used in JavaScript comparisons?.

Abstract Equality (==)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents