Loops in JavaScript
So far, we’ve learned how to store data in variables, arrays, and objects. We’ve also seen how to make decisions with conditionals and reuse logic with functions.
But here’s a question: What if you need to do the same thing over and over again? Like printing every item in a list, or running a block of code 10 times?
You could copy and paste the same code 10 times. But that’s messy, error prone, and impossible when you don’t know how many times you need to repeat something.
That’s where loops come in.
Analogy
Section titled “Analogy”Imagine you’re a teacher with a class of 30 students. You need to hand out a worksheet to each one.
You could walk to each desk, place a sheet, and repeat. Same action, 30 times. You’re not creating 30 different methods for handing out papers. You’re doing one thing in a loop until everyone has a sheet.
That’s exactly how loops work in JavaScript. They let you repeat a block of code multiple times without writing it over and over again.
Let’s explore the different types of loops JavaScript offers.
The for Loop
Section titled “The for Loop”The for loop is the most common and flexible loop. It runs a block of code a specific number of times.
Syntax
Section titled “Syntax”for (initialization; condition; update) {
// code to repeat
}
Here’s what each part does:
- initialization: Runs once at the start. Usually used to declare a counter variable.
- condition: Checked before every iteration. If
true, the loop runs. Iffalse, the loop stops. - update: Runs after each iteration. Usually used to increment or decrement the counter.
Let’s see a simple example:
for (let i = 0; i < 5; i++) {
console.log(`Count: ${i}`);
}
// Outputs: Count: 0, Count: 1, Count: 2, Count: 3, Count: 4
In the above example, we start with i at 0. Before each run, we check if i is less than 5. If yes, we run the code and print the count. Then we add 1 to i and repeat. Once i becomes 5, the condition fails and the loop stops.
Looping Through an Array
Section titled “Looping Through an Array”One of the most common uses of a for loop is to iterate over an array:
const fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Outputs: Apple, Banana, Mango
In the above example, we use i as the index. We start at 0 and go up to fruits.length - 1 (since the condition is i < fruits.length). Each time, we access fruits[i] to get the current element.
The while Loop
Section titled “The while Loop”The while loop keeps running as long as a condition is true. Unlike for, you don’t need to know the number of iterations in advance.
Syntax
Section titled “Syntax”while (condition) {
// code to repeat
}
Example:
let count = 0;
while (count < 3) {
console.log(`Count is ${count}`);
count++;
}
// Outputs: Count is 0, Count is 1, Count is 2
In the above example, the loop runs while count is less than 3. We manually increment count inside the loop. If we forget to update count, the loop would run forever (an infinite loop), which would freeze your program.
When to Use while
Section titled “When to Use while”Use while when you don’t know how many times you need to repeat. For example, reading user input until they type “quit”, or processing data until a certain condition is met.
The do...while Loop
Section titled “The do...while Loop”The do...while loop is similar to while, but with one key difference: it always runs the code block at least once, then checks the condition.
Syntax
Section titled “Syntax”do {
// code to repeat
} while (condition);
Example:
let num = 10;
do {
console.log(num);
num++;
} while (num < 5);
// Outputs: 10
In the above example, the loop runs once and prints 10. Then it checks num < 5. Since 10 is not less than 5, the condition is false and the loop stops. Even though the condition was false from the start, the block ran once.
When to Use do...while
Section titled “When to Use do...while”Use do...while when you need to run the code at least once before checking. For example, asking the user for input and validating it before deciding whether to ask again.
The for...of Loop
Section titled “The for...of Loop”The for...of loop is a simpler way to iterate over iterable values like arrays, strings, and maps. You get the value directly, not the index.
Syntax
Section titled “Syntax”for (const item of iterable) {
// use item
}
Example with an array:
const fruits = ["Apple", "Banana", "Mango"];
for (const fruit of fruits) {
console.log(fruit);
}
// Outputs: Apple, Banana, Mango
In the above example, fruit holds the actual value at each iteration. No need to use fruits[i] or worry about index. Much cleaner and easier to read.
Example with a string:
const name = "JS";
for (const char of name) {
console.log(char);
}
// Outputs: J, S
In the above example, the loop iterates over each character in the string.
When to Use for...of
Section titled “When to Use for...of”Use for...of when you only need the values and don’t care about the index. It’s the preferred loop for arrays and strings when you’re just reading or processing each element.
The for...in Loop
Section titled “The for...in Loop”The for...in loop iterates over the keys (property names) of an object. It’s not meant for arrays.
Syntax
Section titled “Syntax”for (const key in object) {
// use key
}
Example:
const employee = {
name: "John",
age: 25,
department: "Engineering",
};
for (const key in employee) {
console.log(`${key}: ${employee[key]}`);
}
// Outputs: name: John, age: 25, department: Engineering
In the above example, key holds the property name at each iteration. We use employee[key] to get the value.
When to Use for...in
Section titled “When to Use for...in”Use for...in when you need to loop through the keys of an object. It’s not meant for arrays.
Breaking and Continuing
Section titled “Breaking and Continuing”Sometimes you want to exit a loop early or skip an iteration. JavaScript gives you two keywords for that.
The break statement exits the loop immediately, no matter what the condition says.
const numbers = [1, 2, 3, 4, 5];
for (const num of numbers) {
if (num === 4) {
break;
}
console.log(num);
}
// Outputs: 1, 2, 3
In the above example, as soon as we hit 4, we break out of the loop. So 4 and 5 are never printed.
continue
Section titled “continue”The continue statement skips the rest of the current iteration and moves to the next one.
const numbers = [1, 2, 3, 4, 5];
for (const num of numbers) {
if (num === 3) {
continue;
}
console.log(num);
}
// Outputs: 1, 2, 4, 5
In the above example, when we hit 3, we skip the console.log and jump to the next iteration. So 3 is never printed.
Nested Loops
Section titled “Nested Loops”You can put a loop inside another loop. This is useful when working with multi-dimensional data like a grid or a table.
const matrix = [
[1, 2],
[3, 4],
];
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]);
}
}
// Outputs: 1, 2, 3, 4
In the above example, the outer loop goes through each row. The inner loop goes through each element in that row. So we visit every element in the 2D array.
Choosing the Right Loop
Section titled “Choosing the Right Loop”| Loop | Use when |
|---|---|
for |
You know how many times to repeat or need the index |
while |
You don’t know iterations in advance |
do...while |
You need at least one run before checking the condition |
for...of |
You need to iterate over array or string values |
for...in |
You need to iterate over object keys |
Wrapping It Up
Section titled “Wrapping It Up”Loops are the backbone of repetitive tasks in JavaScript. They let you run the same code multiple times without repeating yourself.
You learned how to:
- Use
forloop for counted iterations - Use
whileanddo...whilefor condition-based repetition - Use
for...ofor a regularforloop for arrays and strings - Use
for...infor object keys - Control flow with
breakandcontinue - Use nested loops for multi-dimensional data
Pick the right loop for the task and keep your code clean and efficient.