Skip to content

JavaScript Tutorial Loops

Which JavaScript Loop Should You Use?

Lesson 51 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

JavaScript gives you many ways to repeat code. Here is how to choose.

You want to…Use
Repeat a set number of times, or countfor
Visit every item in an array or stringfor...of
Visit keys and values of an objectfor (const [k, v] of Object.entries(obj))
Repeat until a condition changeswhile
Always run at least once, then repeatdo...while
Build a new array from an old onemap()
Keep only some itemsfilter()
Get one result from many itemsreduce()
Find an item or check a rulefind(), some(), every()

The same task in different styles

Double every number.

script.js
JS
const numbers = [1, 2, 3];

// classic for
const a = [];
for (let i = 0; i < numbers.length; i++) {
  a.push(numbers[i] * 2);
}

// for...of
const b = [];
for (const n of numbers) {
  b.push(n * 2);
}

// map
const c = numbers.map(n => n * 2);

console.log(a, b, c); // → [2, 4, 6] [2, 4, 6] [2, 4, 6]

All three give the same result. The map version says what you want (a new array where each number is doubled). The loops spell out how.

Practical advice

  1. Start with array methods (map, filter, find) when transforming data. They are short and do not need extra variables. See the Arrays chapter.
  2. Use for...of when you need a loop with break, continue, await, or several steps per item.
  3. Use for when the index matters, you step by something other than 1, or you go backwards.
  4. Use while when the end depends on something other than a counter.
  5. Avoid for...in on arrays.

About forEach

forEach calls a function for each item and returns nothing. It cannot be stopped with break, and it does not wait for async work. That is why many developers prefer for...of for side effects (printing, updating the page) and map for creating new arrays.

script.js
JS
["a", "b"].forEach(item => console.log(item));
lightbulb
Readability first
Performance differences between these loops almost never matter for beginner and everyday code. Pick the one that is easiest to read.