DEV Community

Mani Kandan
Mani Kandan

Posted on

Looping in Javascript

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

  1. for Loop

Used when the number of iterations is known.

for (let i = 1; i <= 5; i++) {
console.log(i);
}

  1. while Loop

Used when the number of iterations is unknown.

let i = 1;

while (i <= 5) {
console.log(i);
i++;
}

  1. do...while Loop

Executes the code at least once before checking the condition.

let i = 1;

do {
console.log(i);
i++;
} while (i <= 5);

  1. for...of Loop

Used to iterate through arrays or strings.

let colors = ["Red", "Green", "Blue"];

for (let color of colors) {
console.log(color);
}

  1. 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)