Operators perform operations on one or more operands (variables or values). JavaScript provides arithmetic, comparison, logical, assignment, bitwise, and ternary operators, along with modern operators like nullish coalescing (??) and optional chaining (?.).
flowchart TD
Operators["JavaScript Operators"] --> Arith["Arithmetic (+, -, *, /, %, **)"]
Operators --> Comp["Comparison (===, !==, >, <, >=, <=)"]
Operators --> Logic["Logical (&&, ||, !, ??)"]
Operators --> Ternary["Ternary Condition (? :)"]
| Operator Category | Operators | Example | Result |
|---|---|---|---|
| Strict Comparison | ===, !== |
'5' === 5 |
false (Checks value AND type) |
| Loose Comparison | ==, != |
'5' == 5 |
true (Performs type coercion) |
| Nullish Coalescing | ?? |
null ?? 'Default' |
'Default' (Returns right side ONLY if null/undefined) |
| Logical OR | ` | ` | |
| Optional Chaining | ?. |
user?.address?.city |
undefined (Short-circuits without crashing) |
// Demonstrating modern JavaScript operators
// 1. Strict vs Loose Comparison
console.log("--- Comparison Operators ---");
console.log(`Loose ("10" == 10): ${"10" == 10}`); // true
console.log(`Strict ("10" === 10): ${"10" === 10}`); // false
// 2. Nullish Coalescing (??) vs Logical OR (||)
const userSettings = {
theme: "", // Falsy string
retryCount: 0, // Falsy number
timeout: null // Nullish
};
// Logical OR treats "" and 0 as falsy and replaces them
const themeOR = userSettings.theme || "light"; // "light"
const countOR = userSettings.retryCount || 5; // 5 (Unexpected fallback!)
// Nullish Coalescing preserves valid falsy values ("" and 0)
const themeNullish = userSettings.theme ?? "light"; // ""
const countNullish = userSettings.retryCount ?? 5; // 0 (Correct!)
const timeoutNullish = userSettings.timeout ?? 3000; // 3000
console.log(`Nullish Theme: "${themeNullish}", Retry: ${countNullish}, Timeout: ${timeoutNullish}`);
// 3. Optional Chaining (?.) with Ternary Operator
const account = {
profile: {
getAvatar: () => "https://avatar.example/user.png"
}
};
const avatarUrl = account?.profile?.getAvatar ? account.profile.getAvatar() : "default.png";
console.log(`Avatar URL: ${avatarUrl}`);
=== / !==): Loose equality (==) relies on complex type coercion rules that cause obscure logic bugs.?? Over || for Numeric or String Defaults: Use ?? when 0 or "" are valid user input values.?. Safely: Avoid over-chaining ?. everywhere; use it only when deep properties may genuinely be null or undefined.Evaluate the output of:
0 || 1000 ?? 100Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.