Operators
Operators
Section titled βOperatorsβWhat it means
Section titled βWhat it meansβOperators combine or compare values. JavaScript groups them into arithmetic (+, -, *, /, %, **), comparison (==, ===, <, >=, etc.), logical (&&, ||, !), and a handful of newer, more precise operators like ?? (nullish coalescing) and ?. (optional chaining).
Examples
Section titled βExamplesβconsole.log(10 % 3); // 1 -- remainderconsole.log(2 ** 8); // 256 -- exponentiation
console.log(5 == "5"); // true -- loose equality, coerces typesconsole.log(5 === "5"); // false -- strict equality, no coercion
console.log(true && "yes"); // "yes" -- && returns the last truthy operandconsole.log(false || "default"); // "default"
const port = process.env.PORT ?? 3000; // only falls back for null/undefinedconst city = user?.address?.city; // safely reads nested, possibly-missing propsCommon mistake
Section titled βCommon mistakeβUsing == (loose equality) instead of === (strict equality) β == performs type coercion before comparing, producing surprising results for edge cases.
console.log(0 == ""); // true -- both coerce to falsyconsole.log(0 == "0"); // trueconsole.log("" == "0"); // false -- inconsistent, hard to predictconsole.log(null == undefined); // true
// Strict equality avoids all of this coercionconsole.log(0 === ""); // falseconsole.log(0 === "0"); // falseQuick practice
Section titled βQuick practiceβ-
Whatβs the key difference between
==and===?Answer
==coerces operands to the same type before comparing;===compares both value and type with no coercion.===is almost always the safer choice. -
What does
??do differently from||?Answer
??only falls back onnullorundefined;||falls back on any falsy value, including0,"", andfalse, which is often not what you want. -
What does
user?.address?.cityreturn ifuser.addressisundefined?Answer
undefinedβ optional chaining short-circuits and returnsundefinedinstead of throwing aTypeErrorwhen it hits a null/undefined link in the chain.