JavaScript Loops
Loops in JavaScript are used to repeat a block of code a specific number of times or until a condition is met. They are an essential part of programming for handling repetitive tasks efficiently.
1. For Loop
The for
loop is used when you know in advance how many times you want to execute a statement or a block of statements.
Syntax:
for (initialization; condition; increment) {
// code to be executed
}
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
This example will print the numbers from 0 to 4. The loop starts with i = 0
, and continues as long as i < 5
, incrementing i
by 1 after each iteration.
2. While Loop
The while
loop is used when you want to repeat a block of code an unknown number of times, as long as a specified condition evaluates to true
.
Syntax:
while (condition) {
// code to be executed
}
Example:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Here, the loop runs as long as i < 5
. Each time the loop runs, i
is incremented by 1.
3. Do-While Loop
The do-while
loop is similar to the while
loop, but the code is executed at least once before the condition is tested.
Syntax:
do {
// code to be executed
} while (condition);
Example:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
This loop will behave the same as the while
loop example above, but the condition is checked after the code has run, ensuring that the block executes at least once.
4. For...In Loop
The for...in
loop is used to iterate over the properties of an object.
Syntax:
for (key in object) {
// code to be executed
}
Example:
let person = {name: "John", age: 30, city: "New York"};
for (let key in person) {
console.log(key + ": " + person[key]);
}
This loop will print each property of the object person
and its value. It will print:
name: John
age: 30
city: New York
5. For...Of Loop
The for...of
loop is used to iterate over iterable objects like arrays, strings, or maps.
Syntax:
for (variable of iterable) {
// code to be executed
}
Example:
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
This loop will print each element of the array:
apple
banana
cherry
6. Breaking and Continuing in Loops
Inside loops, you can use the break
statement to stop the loop and the continue
statement to skip to the next iteration of the loop.
Example:
for (let i = 0; i < 5; i++) {
if (i === 3) {
continue; // Skip this iteration
}
if (i === 4) {
break; // Exit the loop
}
console.log(i);
}
This loop will print:
0
1
2
The number 3
is skipped due to the continue
statement, and the loop stops at 4
because of the break
statement.
Conclusion
Loops are one of the most powerful tools in programming, enabling you to execute repetitive tasks in an efficient and manageable way. By mastering for
, while
, and do-while
loops, as well as using iteration techniques like for...in
and for...of
, you’ll be able to write clean and optimized code.