JavaScript Coercion: Understanding == vs ===

I’ve now wrapped up my current deep dive into JavaScript coercion, ending with one of the most misunderstood parts of the language: "==" vs "===" My biggest takeaway is that the right way to understand equality in JavaScript is not by memorising strange examples like: - 5 == "5" - false == 0 - "" == 0 - null == undefined Instead, it is by understanding the actual rules behind them. What I learned is that === and == are backed by different abstract operations in the ECMAScript spec: 1. === → IsStrictlyEqual(x, y) 2. == → IsLooselyEqual(x, y) For ===, the mental model is simple: - if the types differ, the result is false - no cross-type coercion happens But == is not just “convert both sides to numbers”. It follows a case-by-case algorithm. Depending on the values involved, JavaScript may: 1. convert strings to numbers 2. convert booleans to numbers 3. convert objects to primitives 4. apply the special null / undefined rule 5. compare BigInt and Number in a specific way That is why: - 5 == "5" is true - false == 0 is true - null == undefined is true - but null == 0 is false The best part of learning this topic is that JavaScript now feels much less random. I also feel more confident reading the ECMAScript spec now. I do not need to learn every abstract operation in depth, but I know how to navigate the spec when I want to understand why JavaScript produced a certain result. I’ve been maintaining detailed notes on everything I learned here: GitHub repo: https://lnkd.in/ephuZ-w6 #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #ECMAScript

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories