Prefer expressions with explicit meaning
Operators compute, compare or assign values. JavaScript can convert operand types implicitly, so check types before interpreting a result. Strict equality avoids the coercion performed by loose equality.
console.log(5 + 2); // 7
console.log('5' + 2); // 52
console.log(5 === '5'); // false
console.log(5 == '5'); // true
console.log(7 % 3); // 1
console.log(2 ** 3); // 8Assignment versus comparison
= changes a binding or property; === compares without type coercion. An assignment inside a condition can be valid syntax but an unintended bug. Do not rely on a comparison to validate a string input's numeric format; convert and validate separately.
Short-circuit operators return operands
console.log(0 || 10); // 10
console.log(0 ?? 10); // 0
console.log('ready' && 'continue'); // continue
const user = null;
console.log(user?.name ?? 'Guest'); // Guest|| falls back for any falsy left operand. ?? falls back only for null or undefined, so it preserves valid zero and empty-string values. && and || return selected operand values, not necessarily booleans. Optional chaining stops at a nullish target, but does not validate every later value's type.
Precedence and readable grouping
Multiplication binds more tightly than addition: 2+3*4 is 14. Parentheses communicate intent. Do not mix ?? directly with && or || without required parentheses. Keep complex updates in separate statements rather than depending on a reader to decode several side effects.
Identity and special numeric cases
Two separate objects with identical properties are not strictly equal because their identities differ. NaN is not equal to itself. Object.is has deliberate differences for NaN and signed zero; choose the comparison according to the requirement rather than assuming one universal deep-equality operation.
Practice
- Use ?? to supply a default lesson count without replacing a legitimate zero.
- Compare two separately created arrays with ===; expect false.
- Write a range test as
score >= 0 && score <= 100, not a chained mathematical inequality. - Predict
'10' - 2and'10' + 2. Answers: 8 and '102'.