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
05

JavaScript · Lesson 5 of 20 · 4 min

Control Flow: Loops

Interviewers use loops to test your core logic, not just your syntax.

After this, you'll know which loop to use for any given task and how to articulate the trade-offs. This isn't about memorizing five types of loops; it's about choosing the right tool and using it precisely.

The classic for vs. while

Your two most basic looping constructs are the for and while loops. The choice is simple.

Use a for loop when you know the number of iterations in advance, like iterating from 0 to 10 or through the length of an array. Its syntax bundles the counter, condition, and increment together, making it hard to forget a step and create an infinite loop.

Use a while loop when you need to repeat an action until a condition is met, but you don't know how many times that will take. Think polling an API endpoint until it returns a success status, or a game loop that runs as long as the player is alive.

The trap: With while, you are responsible for ensuring the exit condition is eventually met. Forgetting to increment a counter or change a state variable inside the loop is a common way to write an infinite loop that will get your solution rejected.

The do...while loop is a variant that checks the condition after the block, guaranteeing at least one execution. It's rare in practice and even rarer in interviews. Know it exists, but don't spend time on it.

Use for...of for values, not for...in

ES6 introduced the for...of loop. This is now the standard, most readable way to iterate over the values of an iterable like an array or string.

const fruits = ["Apple", "Banana", "Cherry"];
for (const fruit of fruits) {
  console.log(fruit);
}

This is cleaner and less error-prone than a manual for loop with an index.

The trap: Never use a for...in loop to iterate over an array. An interviewer might even bait you with this. The for...in loop iterates over the enumerable property keys of an object, not its values.

For an array, this means it gives you the indices as strings ("0", "1", "2"), and it can also include other properties added to the array's prototype chain, leading to unexpected behavior. Reserve for...in for iterating over plain object keys, and even then, modern methods like Object.keys() are often safer.

Control the flow with break and continue

Sometimes you don't need to complete every iteration. break and continue give you that control.

break terminates the loop entirely. It's for when you've found what you were looking for and any further iteration is wasted work. This is a common micro-optimization.

continue skips the current iteration and moves to the next. It's useful for filtering out items you don't want to process.

This example uses both to find the first active admin in a list of users.

const users = [
  { id: 1, name: 'Alice', role: 'admin' },
  { id: 2, name: 'Bob', role: 'user' },
  { id: 3, name: 'Charlie', role: 'user', disabled: true },
  { id: 4, name: 'Diana', role: 'admin' },
];

function findFirstAdmin(userList) {
  let firstAdmin = null;
  for (const user of userList) {
    if (user.disabled) {
      continue; // Skip disabled users.
    }
    if (user.role === 'admin') {
      firstAdmin = user;
      break; // Found one, stop looking.
    }
  }
  return firstAdmin;
}

console.log(findFirstAdmin(users));
// Output: { id: 1, name: 'Alice', role: 'admin' }

Using break here prevents the loop from needlessly checking Bob, Charlie, and Diana after Alice has already been found.

Avoid off-by-one errors

A frequent source of bugs, and a sign of sloppiness in an interview, is the "off-by-one" error. This happens when your loop runs one too many or one too few times.

It almost always comes down to the condition in a classic for loop. When iterating an array of length n, the valid indices are 0 through n-1.

This is correct and idiomatic: for (let i = 0; i < array.length; i++). The loop stops when i equals array.length, which is correct because array[array.length] is out of bounds.

This is also correct, but less common: for (let i = 0; i <= array.length - 1; i++).

The trap: Using <= with array.length (e.g., i <= array.length) is a classic off-by-one bug. Your last iteration will try to access an index that doesn't exist, resulting in undefined. Interviewers notice this immediately. Double-check your loop boundaries.

Try it

Write a function that solves the FizzBuzz problem. It's a classic screening question that tests your understanding of loops and conditionals in one go. Print numbers from 1 to n. For multiples of three, print "Fizz". For multiples of five, print "Buzz". For multiples of both, print "FizzBuzz".

Next: You'll wrap logic like this into reusable blocks in the next lesson, "Functions: Basics".

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Control Flow: Conditionals

Next

Functions: Basics