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
xisNaN, returnfalse. - If
yisNaN, returnfalse. - If
xis the same number value asy, returntrue. - If
xis+0andyis-0, returntrue. - If
xis-0andyis+0, returntrue. - Otherwise, return
false.
- If
- If
Type(x)isString, returntrueifxandyare exactly the same sequence of characters. Otherwise, returnfalse. - If
Type(x)isBoolean, returntrueifxandyare bothtrueor bothfalse. Otherwise, returnfalse. - If
xandyrefer to the same object, returntrue. Otherwise, returnfalse.
- If
- If
xisnullandyisundefined, returntrue. - If
xisundefinedandyisnull, returntrue. - If
Type(x)isNumberandType(y)isString, return the result of the comparisonx == ToNumber(y). - If
Type(x)isStringandType(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 eitherStringorNumberandType(y)isObject, return the result of the comparisonx == ToPrimitive(y). - If
Type(x)isObjectandType(y)is eitherStringorNumber, 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.
