Operators
📖 Concept
Operators are symbols that perform operations on values. JavaScript has several types:
Arithmetic: +, -, *, /, % (modulo), ** (exponent)
Comparison: == (loose), === (strict), !=, !==, >, <, >=, <=
Logical: && (AND), || (OR), ! (NOT)
Ternary: condition ? valueIfTrue : valueIfFalse
Nullish Coalescing: ?? — returns right side only if left is null/undefined
Optional Chaining: ?. — safely access nested properties
🏠 Real-world analogy: === is like checking if two people are the EXACT same person (same type AND value). == is like checking if they look alike (allows type conversion).
💻 Code Example
1// Arithmetic2console.log(10 % 3); // 1 (remainder)3console.log(2 ** 3); // 8 (exponent)45// Comparison: == vs ===6console.log(5 == "5"); // true (type coercion)7console.log(5 === "5"); // false (strict, no coercion)8console.log(0 == false); // true9console.log(0 === false);// false1011// Logical operators with short-circuit evaluation12const user = { name: "Alice" };13const displayName = user.name || "Anonymous"; // "Alice"14const greeting = user.name && "Hello " + user.name; // "Hello Alice"1516// ⚠️ || vs ?? — critical difference17const count = 0;18console.log(count || 10); // 10 (0 is falsy!)19console.log(count ?? 10); // 0 (?? only checks null/undefined)2021// Ternary operator22const age = 20;23const status = age >= 18 ? "Adult" : "Minor"; // "Adult"2425// Optional chaining26const obj = { a: { b: { c: 42 } } };27console.log(obj?.a?.b?.c); // 4228console.log(obj?.x?.y?.z); // undefined (no error!)
🏋️ Practice Exercise
Mini Exercise:
- Write an expression using the ternary operator that assigns "Even" or "Odd" based on a number
- Use
??to provide a default value for a potentially null variable - Compare the results of
"" || "default"vs"" ?? "default" - Use optional chaining to safely access a deeply nested property
⚠️ Common Mistakes
Using
==instead of===— loose equality causes unexpected type coercion bugsConfusing
||with??—||treats0,"", andfalseas falsy;??only checks fornull/undefinedForgetting that
&&returns the first falsy value (or last value if all truthy), not alwaystrue/falseNot knowing operator precedence — use parentheses to make intent clear
Using
typeofto check fornull— it returns"object", not"null"
💼 Interview Questions
🎤 Mock Interview
Mock interview is powered by AI for Operators. Login to unlock this feature.