JavaScript gives you many ways to repeat code. Here is how to choose.
| You want to… | Use |
|---|---|
| Repeat a set number of times, or count | for |
| Visit every item in an array or string | for...of |
| Visit keys and values of an object | for (const [k, v] of Object.entries(obj)) |
| Repeat until a condition changes | while |
| Always run at least once, then repeat | do...while |
| Build a new array from an old one | map() |
| Keep only some items | filter() |
| Get one result from many items | reduce() |
| Find an item or check a rule | find(), some(), every() |
The same task in different styles
Double every number.
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
- Start with array methods (
map,filter,find) when transforming data. They are short and do not need extra variables. See the Arrays chapter. - Use
for...ofwhen you need a loop withbreak,continue,await, or several steps per item. - Use
forwhen the index matters, you step by something other than 1, or you go backwards. - Use
whilewhen the end depends on something other than a counter. - Avoid
for...inon 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.
["a", "b"].forEach(item => console.log(item));