Careeroza
Type Coercion Rules
How == and + Convert
Example
console.log(1 + "2", 1 - "2"); // + prefers strings, - converts to numbers
console.log([] == false); // [] -> "" -> 0, false -> 0
console.log([1] == 1, [1, 2] == "1,2");
console.log(null + 1, undefined + 1);
console.log({} + [], [] + []);
console.log(+"", +" 42 ", +"4 2", +true);Output
12 -1 true true true 1 NaN [object Object] 0 42 NaN 1
ToPrimitive
Example
Objects are converted with valueOf() / toString() (or Symbol.toPrimitive) before comparison or arithmetic:
const price = {
amount: 499,
valueOf() { return this.amount; },
toString() { return "₹" + this.amount; },
};
console.log(price + 1); // uses valueOf
console.log(`${price}`); // uses toString
console.log(price > 400);Output
500 ₹499 true
Note: Explicit conversion (Number(), String()) and === avoid nearly all coercion surprises.