Skip to main content

Looping in JavaScript

Loops let you repeat actions and iterate over data. JavaScript has several loop types, but you’ll use two of them most of the time: for...of and the classic for loop.

for…of — iterate over arrays

The cleanest way to loop through an array:
const fruits = ["Apple", "Banana", "Cherry"];

for (const fruit of fruits) {
  console.log(fruit);
}
// Apple
// Banana
// Cherry
for (const item of items) {
  console.log(item);
}
JavaScript’s for...of is Python’s for...in. Same concept, different keyword. Use const for the loop variable if you don’t need to reassign it inside the loop.

When you need the index

const users = ["Sarah", "John", "Alice"];

// Use .forEach() with index
users.forEach((user, index) => {
  console.log(`${index + 1}. ${user}`);
});
// 1. Sarah
// 2. John
// 3. Alice

// Or use .entries()
for (const [index, user] of users.entries()) {
  console.log(`${index + 1}. ${user}`);
}
for (const [index, user] of users.entries()) {
  console.log(`${index}: ${user}`);
}
.entries() is JavaScript’s equivalent of Python’s enumerate().

for…in — iterate over object keys

const user = { name: "Sarah", age: 28, role: "admin" };

for (const key in user) {
  console.log(`${key}: ${user[key]}`);
}
// name: Sarah
// age: 28
// role: admin
for...in is for objects. for...of is for arrays. Mixing them up is a common mistake. for...in on an array gives you index strings (“0”, “1”, “2”), not the values.
For objects, you can also use Object.entries() which is often cleaner:
const user = { name: "Sarah", age: 28, role: "admin" };

for (const [key, value] of Object.entries(user)) {
  console.log(`${key}: ${value}`);
}

Classic for loop

The traditional loop with a counter variable. Use it when you need precise control over the iteration:
for (let i = 0; i < 5; i++) {
  console.log(i);
}
// 0, 1, 2, 3, 4
Three parts: for (initialization; condition; update)
  • initialization: let i = 0 — runs once before the loop
  • condition: i < 5 — checked before each iteration
  • update: i++ — runs after each iteration

Practical example

// Generate a grid of items
const rows = 3;
const cols = 4;

for (let row = 0; row < rows; row++) {
  for (let col = 0; col < cols; col++) {
    console.log(`Cell [${row}, ${col}]`);
  }
}

Looping backwards

const items = ["first", "second", "third"];

for (let i = items.length - 1; i >= 0; i--) {
  console.log(items[i]);
}
// third, second, first

while and do…while

For loops where you don’t know the count in advance:
// while — checks condition first
let attempts = 0;
while (attempts < 3) {
  console.log(`Attempt ${attempts + 1}`);
  attempts++;
}

// do...while — runs at least once, checks condition after
let input;
do {
  input = getInput(); // Runs at least once
} while (!isValid(input));
while loops are uncommon in web development. You’ll mostly use for...of for arrays and array methods like .map() and .forEach(). But while is useful for retry logic and polling patterns.

break and continue

Control the flow inside loops:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// break — exit the loop entirely
for (const num of numbers) {
  if (num > 5) break;
  console.log(num);
}
// 1, 2, 3, 4, 5

// continue — skip to the next iteration
for (const num of numbers) {
  if (num % 2 === 0) continue; // Skip even numbers
  console.log(num);
}
// 1, 3, 5, 7, 9

Loops vs array methods

In modern JavaScript, you’ll often choose between a loop and an array method. Here’s when to use each:
TaskUse
Transform each item.map()
Keep some items.filter()
Find one item.find()
Check if something exists.includes() or .some()
Calculate a total.reduce()
Side effects (log, DOM update).forEach() or for...of
Need break/continuefor...of or for
Need the index.forEach() or for...of with .entries()
// Array method approach — usually preferred
const activeUsers = users.filter(u => u.active).map(u => u.name);

// Loop approach — needed for complex logic or early exit
const results = [];
for (const user of users) {
  if (user.role === "banned") continue;
  if (results.length >= 10) break;
  if (user.active) {
    results.push(user.name);
  }
}
Prefer array methods when possible — they’re more readable and less error-prone. Use for...of when you need break, continue, or complex multi-step logic inside the loop.

What’s next?

You’ve covered working with data — arrays, objects, destructuring, spread, JSON, conditionals, and loops. This is the toolbox you’ll use in every web application. Next up: asynchronous JavaScript. This is where things get interesting — you’ll learn how JavaScript handles operations that take time, like fetching data from your FastAPI backend.

Why async matters

Understand why JavaScript handles time differently