Equality and coercion rules are the most common source of surprising results in JavaScript.
The arithmetic operators are + - * /, plus % (remainder) and ** (power). Each has a compound assignment form: x += 2, x **= 2, and ++/-- add or subtract one.
+ is special: if either operand is a string, it concatenates. So "5" + 3 is "53", while "5" - 3 is 2 because - only does math and converts the string to a number.
Comparison uses <, >, <=, >= and two kinds of equality:
===and!==(strict equality): true only if both type and value match. No conversion.==and!=(loose equality): convert operands first using rules that produce results like0 == ""being true.
Always use ===. The one idiom some teams allow is x == null, which is true for both null and undefined.
NaN is not equal to anything, including itself; test it with Number.isNaN(x). Object.is(a, b) is like === but treats NaN as equal to itself and distinguishes 0 from -0.
The logical operators &&, || and ! short-circuit and return one of their operands, not necessarily a boolean:
a || breturnsaif it is truthy, otherwiseb.a && breturnsaif it is falsy, otherwiseb.
That's why name || "Anonymous" works as a default. !!x converts any value to a boolean.
Example
console.log(7 % 3, 2 ** 10); // 1 1024
console.log("5" + 3); // "53" (string concatenation)
console.log("5" - 3); // 2 (numeric)
console.log(0 == ""); // true (loose: avoid)
console.log(0 === ""); // false (strict)
console.log(null == undefined); // true
console.log(NaN === NaN); // false
console.log(Number.isNaN(NaN)); // true
const input = "";
console.log(input || "default"); // "default"
console.log("a" && "b"); // "b"
console.log(!!"text"); // trueRemember
- Use
===/!==; loose==converts types in surprising ways +concatenates if either side is a string; other math operators convert to numbers||and&&return one of their operands, which makes them handy for defaults
Watch out for
- Comparing with
=== NaN, which is always false — useNumber.isNaN.