Module 03 // Core JavaScript

Operators

Module Objective

Arithmetic, logical, comparison, assignment, ternary, nullish coalescing, optional chaining, delete, in, instanceof

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 1. Nullish Coalescing (??) vs OR (||)
let count = 0;

let result1 = count || 10; // OR sees 0 as falsy
console.log(result1); // 10 (Maybe not what you wanted!)

let result2 = count ?? 10; // Nullish only looks for null/undefined
console.log(result2); // 0 (Correct!)
💡 The `||` operator returns the right side if the left is *any* falsy value (0, '', false). The `??` operator only returns the right side if the left is `null` or `undefined`.
// Example 2
// 2. Optional Chaining (?.)
const user = { 
  id: 1, 
  // profile is missing
};

// console.log(user.profile.name); // ❌ Throws Error
console.log(user.profile?.name); // ✅ undefined (Safe!)
💡 Optional chaining `?.` stops evaluation if the value before it is `null` or `undefined`, preventing the dreaded 'Cannot read property of undefined' error.
// Example 3
// 3. Strict Equality (===) vs Loose (==)
console.log(5 == "5");  // true (Coercion happens)
console.log(5 === "5"); // false (Type must match)
console.log(null == undefined); // true
console.log(null === undefined); // false
💡 Always use `===` (strict equality) to avoid unexpected type coercion bugs.

Engine & Memory Architecture

How Operators Work

1. Evaluation:

  • JS Engine evaluates expressions from left to right, following operator precedence (PEMDAS).
  • Intermediary values are stored in temporary registers in the CPU or on the Stack.

2. Short-circuiting:

  • For && and ||, the engine stops as soon as the result is certain.
  • If a is false in a && b, b is never even looked at in memory.

3. Type Coercion:

  • If types don't match, JS will often convert them automatically (Coercion) in the Stack before performing the operation.