The Most Hated Algorithm in Web Development
The Abstract Equality Comparison Algorithm in JavaScript
The algorithm that decides the result of (a == b)
Warning: long post. Continue only if you are interested in JavaScript.
There are many reasons to love JavaScript, but if you hate it, I am pretty sure this is a big reason. JavaScript's equality comparison algorithm is a puzzle with a few rules, and it can lead to some unexpected results if you're not careful.
Today, let's dive into the details of JavaScript's type comparison rules. The ECMAScript specification defines the rules that JavaScript engines follow when comparing different types.
The Algorithm:
- If
Type(x)
is the same asType(y)
, then:- If
Type(x)
isUndefined
, returntrue
. - If
Type(x)
isNull
, returntrue
. - If
Type(x)
isNumber
, then:- If
x
isNaN
, returnfalse
. - If
y
isNaN
, returnfalse
. - If
x
is the same number value asy
, returntrue
. - If
x
is+0
andy
is-0
, returntrue
. - If
x
is-0
andy
is+0
, returntrue
. - Otherwise, return
false
.
- If
- If
Type(x)
isString
, returntrue
ifx
andy
are exactly the same sequence of characters. Otherwise, returnfalse
. - If
Type(x)
isBoolean
, returntrue
ifx
andy
are bothtrue
or bothfalse
. Otherwise, returnfalse
. - If
x
andy
refer to the same object, returntrue
. Otherwise, returnfalse
.
- If
- If
x
isnull
andy
isundefined
, returntrue
. - If
x
isundefined
andy
isnull
, returntrue
. - If
Type(x)
isNumber
andType(y)
isString
, return the result of the comparisonx == ToNumber(y)
. - If
Type(x)
isString
andType(y)
isNumber
, return the result of the comparisonToNumber(x) == y
. - If
Type(x)
isBoolean
, return the result of the comparisonToNumber(x) == y
. - If
Type(y)
isBoolean
, return the result of the comparisonx == ToNumber(y)
. - If
Type(x)
is eitherString
orNumber
andType(y)
isObject
, return the result of the comparisonx == ToPrimitive(y)
. - If
Type(x)
isObject
andType(y)
is eitherString
orNumber
, return the result of the comparisonToPrimitive(x) == y
. - Return
false
.
Why is This Important?
Understanding these rules is crucial for writing reliable JavaScript code, as it can save you from subtle bugs.
Example Pitfalls
console.log(0 == '0'); // true (String gets converted to Number)
console.log(false == ''); // true (Both converted to 0)
console.log([] == 0); // true (Array converted to empty string, then to 0)
console.log(null == undefined); // true
console.log({} == '[object Object]'); // false
If you're curious or have questions about type comparison in JavaScript, don't hesitate to reach out! Let's learn together.
All thanks to Kyle Simpson and his book You Don't Know JS (YDKJS) for explaining this concept beautifully and guiding us through the good, bad, and ugly sides of the language.