Loops in JavaScript let you repeat a block of code multiple times. They are essential for tasks like processing arrays, iterating over object properties, repeating an action until a condition is met, and working with user input or runtime data.
Common loop types include for, for...in, for...of, while, and do...while. Each loop has a slightly different use case, but all revolve around three main ideas: start, condition, and update.
i or count) that changes on each iteration.while, but runs the body at least once before checking the condition.Most loops follow the same logical pattern:
let i = 0;).i < 5).i++).For for loops, all three parts live in the loop header. In while and do...while, you typically put initialization before the loop, the condition in the loop header, and the update inside the loop body.
Objects and arrays are treated differently:
for...in is designed for objects and gives you property names (keys).for...of is designed for iterables and gives you the values directly.The for loop is used when you know in advance how many times you want to execute a block of code. It has three parts inside the parentheses: initialization, condition, and increment/decrement.
// Classic for loop with a counter
for (let i = 0; i < 5; i++) {
console.log("Iteration number:", i);
}
// Looping through an array using a for loop
const fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
The for...in loop iterates over enumerable properties (keys) of an object. It is useful when working with objects to access keys and their values.
const person = {name: "Alice", age: 30, city: "NY"};
for (let key in person) {
console.log(key + ": " + person[key]);
}
Note: Avoid using for...in on arrays if you want numeric indices, as it iterates over keys which can include inherited properties.
The for...of loop iterates over iterable objects such as arrays, strings, Maps, Sets, etc., giving you values directly.
const colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
// Using for...of with a string
const message = "Hello";
for (let char of message) {
console.log(char);
}
The while loop runs as long as a specified condition is true. It checks the condition before each iteration, so if the condition is initially false, the loop body will never run.
let count = 0;
while (count < 3) {
console.log("Count is:", count);
count++;
}
Use case: Waiting for a certain condition that depends on runtime values.
The do...while loop guarantees the loop body executes at least once before the condition is tested. This is useful when the loop code must run initially regardless of the condition.
let number = 0;
do {
console.log("Number is:", number);
number++;
} while (number < 3);
// Runs once even though the condition is false
let n = 5;
do {
console.log("Runs once even though condition is false");
} while (n < 3);
let sum = 0;
for (let i = 1; i <= 5; i++) {
sum += i;
}
console.log("Sum of numbers from 1 to 5 is:", sum);
Using for...in for object properties and for...of for array values:
// Iterating over an object
const book = {title: "1984", author: "Orwell"};
for (let prop in book) {
console.log(`${prop}: ${book[prop]}`);
}
// Iterating over an array
const numbers = [10, 20, 30];
for (const num of numbers) {
console.log(num);
}
for loop:
Iteration number: 0 Iteration number: 1 Iteration number: 2 Iteration number: 3 Iteration number: 4
Sum from 1 to 5 is: 15
while loop with count < 3:
Count is: 0 Count is: 1 Count is: 2
do...while loop with number < 3:
Number is: 0 Number is: 1 Number is: 2
Notice how do...while runs its body at least once, even if the condition is false. In the second do...while example with n = 5 and condition n < 3, the message still prints one time.
Click the button to see a simple for loop generate numbers from 1 to 5 and display them on the page.
Click the button above to generate the numbers.
for when you know the exact number of iterations.for...in for enumerating object properties (keys).for...of for iterating over iterable collections like arrays and strings.while or do...while when the number of iterations depends on a condition that changes during runtime.do...while ensures code runs at least once.for...in on arrays; it may include unexpected keys or inherited properties.break and continue intentionally to control loop flow (e.g., exit early or skip an iteration).for loop to print even numbers from 2 to 20.for...in to list keys of an object representing a car.for...of to print each character of a string.while loop that counts down from 10 to 0.do...while loop that keeps asking a user for a password until it matches a stored password.