JavaScript Operators & Strict Equality
Mastering JavaScript operators: arithmetic, logical (&&, ||, ??), comparison (== vs ===), optional chaining (?.), and ternary expressions.
JavaScript Operators & Strict Equality
Operators perform mathematical calculations, string concatenations, logical evaluations, and conditional assignments.
1. Strict (===) vs. Loose (==) Equality
Always use Strict Equality (===). Loose equality (==) performs unpredictable type coercion:
// β Loose Equality (Performs Coercion)
0 == false; // true
"" == false; // true
null == undefined; // true
"42" == 42; // true
// β
Strict Equality (Compares Type AND Value)
0 === false; // false
"" === false; // false
null === undefined; // false
"42" === 42; // false2. Logical Operators & Short-Circuit Evaluation
| Operator | Name | Short-Circuit Rule | Example |
|---|---|---|---|
&& | Logical AND | Returns first falsy value, or last truthy value | user.isAdmin && renderAdminPanel() |
|| | Logical OR | Returns first truthy value, or last falsy value | const name = input || "Anonymous" |
?? | Nullish Coalescing | Returns right-hand value ONLY if left-hand is null or undefined | const port = process.env.PORT ?? 3000 |
Why ?? is Better than || for Defaults:
const count = 0;
// β Bug: 0 is falsy, so || overrides it to 10
const pageSize1 = count || 10; // 10
// β
Correct: 0 is not null/undefined, so ?? preserves 0
const pageSize2 = count ?? 10; // 03. Optional Chaining (?.)
Optional chaining prevents TypeError: Cannot read properties of undefined when traversing deeply nested properties that might not exist:
const user = {
profile: null,
};
// β Crashes with TypeError: Cannot read properties of null
// const city = user.profile.address.city;
// β
Safe: returns undefined immediately without throwing
const city = user.profile?.address?.city;
console.log(city); // undefined4. Conditional (Ternary) Operator
A concise inline replacement for if...else statements:
const status = isOnline ? "Active" : "Offline";Related Topics
JavaScript Data Types & Type Coercion
Mastering JavaScript data types: 7 primitives (string, number, bigint, boolean, undefined, null, symbol), Objects, typeof operator, and type coercion.
JavaScript Conditions (if, else, switch, truthy/falsy)
Control flow in JavaScript: if/else branching, switch statements, truthy vs. falsy values, and early return guard clauses.