What is the Abstract Equality Comparison algorithm?
Answer
The Abstract Equality Comparison algorithm defines the rules JavaScript uses for the == operator. Key rules: same type → use strict equality. null == undefined → true (only these two are loosely equal to each other, nothing else). If one is a Number and the other is a String → convert String to Number. If one is Boolean → convert it to Number (true→1, false→0) then re-compare. If one is an Object and the other is String/Number/Symbol → call ToPrimitive(object) (tries valueOf() then toString()) and compare. This explains famous quirks: [] == false: false→0, []→0 (via valueOf()→[] then toString()→"" then Number("")→0) → true. "" == 0: Number("")→0 → true. [] == ![]: ![]→false, then →0, []→0 → true. These counterintuitive results are why === should almost always be used. Understanding this algorithm explains every "JavaScript is broken" meme. The == operator should be reserved for null/undefined checks: if (val == null) covers both null and undefined cleanly.
Previous
What is lazy evaluation and infinite sequences in JavaScript?
Next
What is the JavaScript Event Loop in depth?