JavaScript silently converts values when an operator expects another type. Learn the three conversions (to string, number, boolean) and == stops being magic.
Explicit conversion
console.log(String(123), String(null), String([1, 2]), String({}));
console.log(Number("42"), Number(""), Number(" 7 "), Number("4px"));
console.log(Number(true), Number(null), Number(undefined), Number([]), Number([5]));
console.log(parseInt("4px"), parseFloat("3.5em"), parseInt("0x1F"), parseInt("101", 2));
console.log(Boolean(""), Boolean("0"), Boolean([]), Boolean(0));123 null 1,2 [object Object]
42 0 7 NaN
1 0 NaN 0 5
4 3.5 31 5
false true true false| Value | Number(v) | String(v) | Boolean(v) |
|---|---|---|---|
undefined | NaN | "undefined" | false |
null | 0 | "null" | false |
true / false | 1 / 0 | "true" / "false" | same |
"" | 0 | "" | false |
"12abc" | NaN | same | true |
[] | 0 | "" | true |
{} | NaN | "[object Object]" | true |
Implicit coercion by operators
+with any string operand → string concatenation. Otherwise numeric addition.- * / % **and unary+→ always numeric.if,!,&&,||,? :→ boolean (truthiness).Objects are first turned into primitives via
Symbol.toPrimitive, thenvalueOf(), thentoString().
console.log(1 + "2", "3" - 1, "3" * "4", +"5", +"");
console.log(true + 1, null + 1, undefined + 1);
console.log([] + [], [] + {}, [1, 2] + [3]);
console.log(1 + 2 + "3", "1" + 2 + 3);12 2 12 5 0
2 1 NaN
[object Object] 1,23
33 123== (loose) vs === (strict)
console.log(0 == "", 0 == "0", "" == "0");
console.log(false == "0", false == [], null == 0, null == undefined);
console.log([1] == 1, [1, 2] == "1,2", NaN == NaN);
console.log(0 === "", null === undefined, 1 === 1.0);true true false
true true false true
true true false
false false trueObject.is — SameValue
console.log(NaN === NaN, Object.is(NaN, NaN));
console.log(0 === -0, Object.is(0, -0));
console.log([NaN].includes(NaN), [NaN].indexOf(NaN));false true
true false
true -1| Algorithm | Used by | NaN vs NaN | 0 vs -0 |
|---|---|---|---|
Strict (===) | ===, indexOf, switch | not equal | equal |
| SameValueZero | includes, Map/Set keys | equal | equal |
| SameValue | Object.is | equal | not equal |
Objects to primitives
const price = {
valueOf() { return 42; },
toString() { return "$42"; },
};
console.log(price + 1, `${price}`, price > 40);
const temp = {
[Symbol.toPrimitive](hint) {
return hint === "number" ? 21 : hint === "string" ? "21°C" : "default";
},
};
console.log(+temp, `${temp}`, temp + "");43 $42 true
21 21°C defaultWhat is the difference between == and ===?
What does [] + {} evaluate to?