JavaScript Coercion: Understanding the 5-Step Process

JavaScript type coercion isn't magic. It's a spec. Every unexpected output follows the same rules, in the same order: 1. Identify the operator 2. If an object is involved → call valueOf(), then toString() 3. If operator is + and either side is a string → concatenate 4. If operator is -, *, / → convert both sides to numbers 5. Compute That's it. Five steps. Runs every time. --- Where this breaks production code: [10] + [1] = "101" → Arrays are objects. valueOf() returns the array itself (not a primitive), so toString() runs next. [10].toString() = "10", [1].toString() = "1". Then + sees two strings. Concatenates. [10] - [1] = 9 → - forces ToNumber. [10] → 10, [1] → 1. Subtracts normally. Boolean([]) = true → [] is not in the falsy list. Truthy. "0" == false → true, but Boolean("0") → true → == coerces both sides to number first. Boolean() checks the falsy list directly. input.value, localStorage, URLSearchParams → Always strings. Wrap with Number() or parseInt() before any arithmetic. --- The complete falsy list (memorise this, not the edge cases): false / 0 / -0 / 0n / "" / null / undefined / NaN Eight values. Everything else is truthy. --- Use === by default. Use == only when you explicitly want coercion — and you almost never do. The spec is 20 years old. The bugs are still new because developers skip the fundamentals. #JavaScript #WebDev #Frontend #SoftwareEngineering #Programming

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories