Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
JavaScript for Frontend Interviews
  1. 1.Introduction to JavaScript & Setup
  2. 2.Variables and Data Types
  3. 3.Operators and Expressions
  4. 4.Control Flow: Conditionals
  5. 5.Control Flow: Loops
  6. 6.Functions: Basics
  7. 7.Arrays and Objects
  8. 8.Higher-Order Functions & Callbacks
  9. 9.Scope and Closures
  10. 10.`this` Keyword and Context
  11. 11.Asynchronous JavaScript: Callbacks & Promises
  12. 12.ES6+ Features (Part 1)
  13. 13.ES6+ Features (Part 2)
  14. 14.Error Handling & Debugging
  15. 15.Asynchronous JavaScript: Async/Await
  16. 16.Prototypal Inheritance & `new` Keyword
  17. 17.Event Loop, Microtasks & Macrotasks
  18. 18.Working with the DOM
  19. 19.Advanced Array Methods & Data Structures
  20. 20.Frontend Interview Prep & Best Practices
JavaScript for Frontend Interviews
04

JavaScript · Lesson 4 of 20 · 4 min

Control Flow: Conditionals

Your ability to write clean, readable conditional logic is a direct signal of your experience.

After this lesson, you will be able to take a messy, nested block of if statements and refactor it into clean, professional code. This is a common task in interviews and on the job.

Flatten nested if statements with guard clauses

Deeply nested if statements are a red flag. They are hard to read, hard to test, and hard to modify. This "pyramid of doom" signals inexperience. The professional alternative is to use "guard clauses" or "early returns."

A guard clause checks for a failure condition at the beginning of a function and exits immediately. This flattens the code, leaving the main logic at the end, un-nested and clear.

The interview angle: You might be given a function with nested ifs and asked to "make it better." Refactoring to use guard clauses is the expected answer. It shows you prioritize readability and maintainability.

Consider this logic for determining user permissions.

// Before: Nested and hard to follow
function getPermissions(user, isAuthenticated, hasPremiumAccess) {
  let permissions = "limited"; // Default permission
  if (isAuthenticated) {
    if (user.role === "admin") {
      permissions = "full";
    } else if (user.role === "editor") {
      if (hasPremiumAccess) {
        permissions = "full";
      } else {
        permissions = "editor-basic";
      }
    } else if (user.role === "viewer") {
      permissions = "read-only";
    }
  }
  return permissions;
}

// After: Flat, clear, and easy to read
function getPermissionsRefactored(user, isAuthenticated, hasPremiumAccess) {
  if (!isAuthenticated) {
    return "limited"; // Guard clause
  }
  if (user.role === "admin") {
    return "full"; // Guard clause
  }
  if (user.role === "editor") {
    return hasPremiumAccess ? "full" : "editor-basic"; // Ternary for simple branch
  }
  if (user.role === "viewer") {
    return "read-only";
  }
  return "limited"; // Default case
}

The second version is instantly easier to understand. Each condition is handled and the function exits. There's no mental stack to keep track of.

Choose the right tool: switch, else if, and ternary

A long if/else if chain checking the same variable is often a sign you should use a switch statement. A switch is cleaner when you're comparing one value against multiple static options.

The trap: Forgetting the break keyword. Without break, execution "falls through" to the next case. This is a common source of bugs. While intentional fall-through has its uses, it's rare and should be commented explicitly.

// 'status' can be 'pending', 'shipped', 'delivered'
switch (status) {
  case 'pending':
    console.log('Order is pending.');
    break; // <-- Crucial
  case 'shipped':
    console.log('Order has shipped.');
    break; // <-- Crucial
  case 'delivered':
    console.log('Order was delivered.');
    break;
  default:
    console.log('Unknown status.');
}

For a simple if/else that results in an assignment, the ternary operator (? :) is a concise option.

const message = isLoggedIn ? 'Welcome' : 'Please log in';

The trap: Overusing the ternary operator. It is for simple, readable assignments only. Never nest them. If the logic requires more than a single expression on either side, use a standard if/else. Code is read more often than it is written.

How JavaScript decides what's true

Any value can be used in a conditional. JavaScript will convert it to a boolean. You must know which values are "falsy."

There are only a handful of falsy values:

  • false
  • 0 (and -0)
  • "" (empty string)
  • null
  • undefined
  • NaN

Every other value is "truthy," including [], {}, " ", and any non-zero number.

The "gotcha" question: An interviewer might ask if ([]) { console.log('hi') }, what happens? The answer is "hi" gets logged, because an empty array is an object, and all objects are truthy.

This is also where the classic == vs === discussion comes up.

  • == (loose equality) performs type coercion. '5' == 5 is true. This leads to unpredictable behavior ('' == 0 is true).
  • === (strict equality) does not coerce types. '5' === 5 is false.

The rule is simple: always use ===. The rare cases where == is useful (like value == null to check for both null and undefined) are not worth the risk of bugs.

Leverage short-circuiting

Logical operators && (AND) and || (OR) don't just return true or false. They evaluate from left to right and "short-circuit."

  • A && B: If A is falsy, the expression short-circuits and returns A. It never even evaluates B. If A is truthy, it returns B.
  • A || B: If A is truthy, the expression short-circuits and returns A. It never evaluates B. If A is falsy, it returns B.

This is not just trivia; it's used for practical patterns.

Conditional property access (before optional chaining ?.): user && user.address && user.address.street This prevents a TypeError if user or user.address is null or undefined.

Providing default values: const name = incomingName || 'Guest'; If incomingName is an empty string, null, or undefined, name will be 'Guest'. Be aware this also triggers on a valid 0. For that, the nullish coalescing operator (??) is better, as it only triggers on null or undefined.

Try it

Take the getPermissions function from the first section. Refactor it to use a switch statement for the user.role check, while still keeping the guard clause for authentication. This will combine two of the key ideas from this lesson.

Next: You'll learn how to repeat actions without repeating code in Control Flow: Loops.

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Operators and Expressions

Next

Control Flow: Loops