Loops are used to execute a block of code repeatedly as long as a specified condition is true. They are essential for handling repetitive tasks, traversing data structures (like arrays and objects), and reducing code redundancy.
The for loop is the most versatile and commonly used loop. It allows you to define the
initialization, condition, and increment/decrement in a single line.
for (initialization; condition; update) {
// code block to be executed
}
// Print numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log("Iteration: " + i);
}
The while loop executes a block of code as long as the specified condition evaluates to
true. It is useful when the number of iterations is not known beforehand.
while (condition) {
// code block to be executed
}
let count = 1;
while (count <= 3) {
document.write("Count is: " + count);
count++;
}
The do...while loop is similar to the while loop, but it guarantees that the code
block is executed at least once before checking the condition.
do {
// code block to be executed
} while (condition);
let num = 5;
do {
document.write("Number: " + num);
num++;
} while (num < 5); // Condition is false, but runs once
The for...in loop is designed to iterate over the properties (keys) of an object. It can
also iterate over array indices, but for...of is preferred for arrays.
const person = {
name: "Ragini",
age: 25,
city: "Delhi"
};
for (let key in person) {
document.write(key + ": " + person[key]);
}
The for...of loop was introduced in ES6. It iterates over the values of iterable objects
such as Arrays, Strings, Maps, and Sets.
const colors = ["Red", "Green", "Blue"];
for (let color of colors) {
document.write(color);
}
const message = "Hello";
for (let char of message) {
document.write(char);
}
break: Terminates the loop entirely.
continue: Skips the current iteration and proceeds to the next one.
document.write("--- Break Example ---");
for (let i = 1; i <= 5; i++) {
if (i === 3) {
document.write("Breaking at 3");
break;
}
document.write(i);
}
document.write("\n--- Continue Example ---");
for (let i = 1; i <= 5; i++) {
if (i === 3) {
document.write("Skipping 3");
continue;
}
document.write(i);
}
| Loop Type | Description | Use Case |
|---|---|---|
| for | Standard loop with counters | Known number of iterations |
| while | Loops while condition is true | Unknown iterations |
| do...while | Loops at least once | Run at least once |
| for...in | Iterates over keys | Object properties (Keys) |
| for...of | Iterates over values | Iterable values (Arrays) |
for...of for arrays to get values directly. Use
for...in for objects. Avoid for...in for arrays as order is not guaranteed.
Test your understanding of JavaScript Loops.
for loop.while and do...while loops.while loop that might never execute.do...while loop that executes at least once.for...of.let fruits = ["apple", "banana", "cherry"];for...of loop to iterate through the array.continue statement.continue statement to skip it.for loops.