Introduction to Loops
In JavaScript, loops help us repeat tasks without writing the same lines of code again and again. Instead of copying and pasting similar code, we can use loops to run the same block of code multiple times. This saves time and keeps the code clean and easy to manage, especially when working with lists or doing something many times.
Why We Use Loops
We use loops when we want to do something over and over. For example, if you want to print numbers from 1 to 10, you don’t need to write 10 console.log()
lines. A loop can do it in just a few lines. Loops help make your code faster to write and easier to change later.
Types of Loops in JavaScript
JavaScript has a few types of loops. Each one is useful in different situations.
1. for loop This loop runs a block of code a certain number of times.
for (let i = 0; i < 5; i++) {
console.log(i);
}
2. while loop This loop keeps running as long as a condition is true.
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
3. do...while loop
This is like a while
loop, but it runs the code at least once, even if the condition is false at the start.
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
4. for...of loop This loop is great for going through items in an array.
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
5. for...in loop This one is used to loop through properties of an object.
let person = { name: "Alice", age: 25 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
Loop Control: break and continue
break
You use break
to stop the loop early, even if the condition is still true.
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log(i);
}
continue
You use continue
to skip one loop step and move to the next.
for (let i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i);
}
Looping Over Arrays
One of the most common uses for loops is going through arrays. You can use a for
loop or a for...of
loop to look at each item and do something with it.
let colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
Or with for...of
:
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
Nested Loops
Sometimes, we need to use a loop inside another loop. This is called a nested loop. For example, to create a multiplication table:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(i * j);
}
}