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

codeTap to expand ⛶
1// Arithmetic
2console.log(10 % 3); // 1 (remainder)
3console.log(2 ** 3); // 8 (exponent)
4
5// Comparison: == vs ===
6console.log(5 == "5"); // true (type coercion)
7console.log(5 === "5"); // false (strict, no coercion)
8console.log(0 == false); // true
9console.log(0 === false);// false
10
11// Logical operators with short-circuit evaluation
12const user = { name: "Alice" };
13const displayName = user.name || "Anonymous"; // "Alice"
14const greeting = user.name && "Hello " + user.name; // "Hello Alice"
15
16// ⚠️ || vs ?? — critical difference
17const count = 0;
18console.log(count || 10); // 10 (0 is falsy!)
19console.log(count ?? 10); // 0 (?? only checks null/undefined)
20
21// Ternary operator
22const age = 20;
23const status = age >= 18 ? "Adult" : "Minor"; // "Adult"
24
25// Optional chaining
26const obj = { a: { b: { c: 42 } } };
27console.log(obj?.a?.b?.c); // 42
28console.log(obj?.x?.y?.z); // undefined (no error!)

🏋️ Practice Exercise

Mini Exercise:

  1. Write an expression using the ternary operator that assigns "Even" or "Odd" based on a number
  2. Use ?? to provide a default value for a potentially null variable
  3. Compare the results of "" || "default" vs "" ?? "default"
  4. Use optional chaining to safely access a deeply nested property

⚠️ Common Mistakes

  • Using == instead of === — loose equality causes unexpected type coercion bugs

  • Confusing || with ??|| treats 0, "", and false as falsy; ?? only checks for null/undefined

  • Forgetting that && returns the first falsy value (or last value if all truthy), not always true/false

  • Not knowing operator precedence — use parentheses to make intent clear

  • Using typeof to check for null — it returns "object", not "null"

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for Operators. Login to unlock this feature.