Operators Overview
Operators are symbols that perform operations on values. JavaScript has a rich set of operators for arithmetic, comparison, logical operations, and more.
// Arithmetic operators
let a = 10, b = 3;
console.log(a + b); // 13 (addition)
console.log(a - b); // 7 (subtraction)
console.log(a * b); // 30 (multiplication)
console.log(a / b); // 3.333... (division)
console.log(a % b); // 1 (modulus/remainder)
console.log(a ** b); // 1000 (exponentiation)
// Increment and decrement
let x = 5;
console.log(x++); // 5 (returns THEN increments)
console.log(x); // 6
console.log(++x); // 7 (increments THEN returns)
console.log(x--); // 7 (returns THEN decrements)
console.log(x); // 6
Comparison & Logical Operators
// Comparison operators โ always return boolean
5 > 3; // true
5 < 3; // false
5 >= 5; // true
5 <= 4; // false
// Equality โ ALWAYS use ===
5 === 5; // true โ strict (checks type + value)
5 === "5"; // false โ different types
5 == "5"; // true โ loose (coerces types, AVOID)
5 !== 3; // true โ strict not-equal
5 != "5"; // false โ loose not-equal (AVOID)
// Logical operators
true && true; // true (AND)
true && false; // false
true || false; // true (OR)
false || false; // false
!true; // false (NOT)
!false; // true
// Short-circuit evaluation โ very important pattern!
// && returns first falsy value, or last value if all truthy:
false && anything; // false (doesn't evaluate 'anything')
0 && "hello"; // 0
"hello" && 42; // 42
// || returns first truthy value, or last value if all falsy:
false || "default"; // "default"
null || undefined || "fallback"; // "fallback"
"value" || "default"; // "value"
// Practical use of short-circuit:
const user = null;
const name = user && user.name; // null (safe โ no error)
const display = name || "Guest"; // "Guest"
// Nullish coalescing โ ?? (ES2020)
// Returns right side only if left is null or undefined (not 0 or "")
const value = null ?? "default"; // "default"
const zero = 0 ?? "default"; // 0 (0 is not null/undefined!)
Assignment Operators
let score = 10;
score += 5; // score = score + 5 โ 15
score -= 3; // score = score - 3 โ 12
score *= 2; // score = score * 2 โ 24
score /= 4; // score = score / 4 โ 6
score **= 2; // score = score ** 2 โ 36
score %= 10; // score = score % 10 โ 6
// Logical assignment (ES2021)
let a = null;
a ||= "default"; // a = a || "default" โ "default"
let b = "existing";
b ||= "default"; // b stays "existing"
let c = null;
c ??= "fallback"; // c = c ?? "fallback" โ "fallback"
let d = 5;
d &&= d * 2; // d = d && d*2 โ 10 (only assigns if d is truthy)
Optional Chaining (?.) โ ES2020
One of the most useful modern operators. Safely access nested properties without throwing errors if intermediate values are null/undefined:
const user = {
name: "Alice",
address: {
city: "New York",
zip: "10001"
}
};
// Old way โ verbose and error-prone:
const city = user && user.address && user.address.city;
// New way โ clean and safe:
const city = user?.address?.city; // "New York"
const country = user?.address?.country; // undefined (no error!)
// Works on methods too:
const result = user.getProfile?.(); // undefined if method doesn't exist
// Works on arrays:
const first = arr?.[0]; // undefined if arr is null/undefined
// Combine with nullish coalescing:
const displayCity = user?.address?.city ?? "Unknown city";
// Practical example with API data:
function displayUser(userData) {
const name = userData?.profile?.displayName ?? userData?.name ?? "Anonymous";
const avatar = userData?.media?.avatar?.url ?? "/default-avatar.png";
return { name, avatar };
}
Operator Precedence
// Operators have precedence (like math BODMAS/PEMDAS)
// Higher precedence executes first
// Parentheses override everything:
2 + 3 * 4; // 14 (multiplication first)
(2 + 3) * 4; // 20 (parentheses first)
// Common precedence order (high to low):
// 1. () - grouping
// 2. ** - exponentiation
// 3. * / % - multiplication, division, modulo
// 4. + - - addition, subtraction
// 5. > < >= <= - comparisons
// 6. === !== - equality
// 7. && - logical AND
// 8. || - logical OR
// 9. ?? - nullish coalescing
// 10. = += -= etc - assignment
// When in doubt, use parentheses:
const result = (a > 0 && b > 0) || (c !== null && d !== undefined);
// Much clearer than:
// const result = a > 0 && b > 0 || c !== null && d !== undefined;
โก Key Takeaways
- Always use
===(strict equality) โ never== &&and||short-circuit โ use for default values and guards??(nullish coalescing) only falls back on null/undefined, not 0 or ""?.(optional chaining) safely access nested properties**is the exponentiation operator:2 ** 10 === 1024- Use parentheses when precedence is unclear โ clarity beats cleverness
๐ฏ Practice Exercises
EXERCISE 1
Write expressions that use short-circuit evaluation to: (1) default a variable to 0 if it's null, (2) call a method only if an object exists, (3) check two conditions at once.
EXERCISE 2
Given a deeply nested object { a: { b: { c: 42 } } }, access a.b.c, a.b.d, and a.x.y safely using optional chaining. What does each return?
EXERCISE 3 โ CHALLENGE
Build a safe property accessor function get(obj, path) where path is a string like "user.address.city". It should return the value or undefined if any part of the path is missing.