Everything, Everywhere
Verified Specification | Standardized Formulas | Instant Precision
Secure & Private (Zero Data Retention) Free Access • No Sign-Up

Conditionals

Conditionals allow your code to take different paths depending on whether an expression evaluates to true or false.

Try It Yourself

      
📋 Copy JavaScript Conditionals & Switch Template
const status = "success";

// Switch Statement with Block Scoping
switch (status) {
  case "loading": {
    const spinner = true;
    break;
  }
  case "success": {
    const data = fetchCached();
    break;
  }
  default:
    throw new Error(`Unhandled status: ${status}`);
}

// Optional Chaining with Nullish Coalescing
const street = user?.address?.street ?? "Unknown Street";

⚠️ 5 Fatal Traps & JavaScript Pitfalls

Trap #1: Switch Statement Fallthrough Bug
Omitting a break statement causes execution to fall through into subsequent case statements regardless of whether their condition matched.
Trap #2: Lexical Scope Clashes Inside Switch Cases
Variables declared with let or const inside a switch statement share a single block scope unless wrapped in curly braces case "x": { const a = 1; break; }.
Trap #3: Optional Chaining on Non-Function Properties
Calling obj?.method() prevents errors if obj is null/undefined, but if method exists and is NOT a function, it still throws a TypeError: obj.method is not a function.
Trap #4: Unintended Assignment in If Statement
Typing if (status = "admin") assigns the string instead of comparing it, mutating the variable and always evaluating to truthy.
Trap #5: Deep Nested Ternary Readability Nightmare
Chaining multiple ternaries (a ? b : c ? d : e ? f : g) obscures business logic. Flatten code using early returns or object strategy dictionaries.

💬 Frequently Asked Questions

What does the optional chaining operator (?.) do in JavaScript?
?. permits reading properties or calling methods deep within an object chain without having to validate that each reference in the chain is non-null.
When should you use an object lookup map instead of switch/case?
Object lookup maps (e.g. const actions = { add: fn1, delete: fn2 }; actions[cmd]?.()) are cleaner, support dynamic additions, and execute in O(1) time.
How does JavaScript handle switch comparisons?
Switch statements use strict equality (===) comparison without type coercion.
What is the guard clause pattern?
A guard clause is a conditional check at the start of a function that handles error states and returns early, avoiding deeply nested if/else blocks.
Can you use destructuring inside an if statement condition?
No, but you can destructure before the condition or use the logical assignment operators (&&=, ||=, ??=).
Sponsored Utility
While You're Here
Sponsored Recommendations
Advertisement