JavaScript Loops: for, while and for...of
JavaScript loops repeat a block of code so you can process a list or perform a task while a condition is true. Learn when to use for, while and for...of.
Quick answer: Use a for loop when you need a counter, a for...of loop to read values from an iterable such as an array, and a while loop when repetition depends on a condition. Make sure each loop can reach its stopping condition.
Repeat a known number of times with for
A for loop combines a starting value, a condition and an update. The browser checks the condition before each run, then performs the update after the loop body.
for (let count = 1; count <= 3; count++) {
console.log("Step " + count);
}
This prints three steps. The variable declared with let is limited to the loop, which helps avoid accidental changes elsewhere in your script.
Read array values with for...of
Use for...of when you want each value in an array or another iterable. It is often clearer than managing an index yourself.
const tasks = ["plan", "write", "review"];
for (const task of tasks) {
console.log(task);
}
If you also need an item number, an indexed for loop or entries() can provide both the index and value.
Repeat while a condition is true
A while loop is useful when you do not know the number of repetitions ahead of time. Change the value used by its condition so the loop can eventually stop.
let attempts = 0;
while (attempts < 3) {
console.log("Attempt " + (attempts + 1));
attempts++;
}
Use break and continue
break exits the current loop. continue skips the rest of the current iteration and moves to the next one.
for (const score of [42, 68, 91, 75]) {
if (score < 50) {
continue;
}
console.log(score);
}
When should I use each JavaScript loop?
Choose the loop form that makes the stopping rule easiest to understand:
forworks well for a counter or a known range of indexes.for...ofworks well for reading values from arrays and strings.whileworks well when a condition controls when repetition ends.
How do I loop through an array in JavaScript?
Use for...of to process each value, or use an indexed for loop if the index is needed. For transforming a list into another list, an array method such as map() may express the goal more directly.
What is the difference between for...of and for...in?
for...of reads values from an iterable. for...in enumerates property names on an object; for ordinary arrays, use for...of or an array method to work with the values.
Practice: total a list of prices
Create an array of three numbers, start a total at zero and use a loop to add each price. Then log the total. This combines arrays, variables and repetition in a small task.