Introduction
Loops in JavaScript are used to execute a block of code repeatedly until a specified condition is met. They help reduce code duplication, improve readability, and make programs more efficient.
Types of Loops
- for Loop
Used when the number of iterations is known.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
- while Loop
Used when the number of iterations is unknown.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
- do...while Loop
Executes the code at least once before checking the condition.
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
- for...of Loop
Used to iterate through arrays or strings.
let colors = ["Red", "Green", "Blue"];
for (let color of colors) {
console.log(color);
}
- for...in Loop
Used to iterate through object properties.
let student = {
name: "Mani",
age: 22
};
for (let key in student) {
console.log(key + ": " + student[key]);
}
Loop Control Statements
break – Stops the loop.
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i);
}
continue – Skips the current iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
}
Conclusion
JavaScript loops simplify repetitive tasks and make code cleaner and more efficient. Understanding for, while, do...while, for...of, and for...in loops is essential for writing effective JavaScript programs.
Top comments (0)