Loops in JavaScript are used to execute a block of code multiple times until a specific condition is met. This prevents repetition and makes the code more efficient.
for
LoopThe for
loop is used when the number of iterations is known in advance.
for (initialization; condition; increment/decrement) {
// Code to execute
}
for (let i = 1; i <= 5; i++) {
console.log("Iteration:", i);
}
π This loop runs 5 times, increasing i
from 1
to 5
.
while
LoopThe while
loop executes a block of code as long as the condition is true
.
let i = 1;
while (i <= 5) {
console.log("Iteration:", i);
i++;
}
π This runs while i
is ≤ 5, incrementing i
in each loop.
do...while
LoopThe do...while
loop executes the code at least once, then continues while the condition is true
.
let i = 1;
do {
console.log("Iteration:", i);
i++;
} while (i <= 5);
π This loop executes once, even if the condition is false
initially.
for...in
Loop (Used for Objects)The for...in
loop iterates over the properties (keys) of an object.
let student = { name: "John", age: 21, grade: "A" };
for (let key in student) {
console.log(key + ": " + student[key]);
}
π This prints each key-value pair from the object.
for...of
Loop (Used for Arrays)The for...of
loop iterates over the values of an array.
let numbers = [10, 20, 30, 40];
for (let num of numbers) {
console.log(num);
}
π This prints each element in the array.
break
Statementfor (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i);
}
// Output: 1, 2
π Loop stops when i === 3
.
continue
StatementSkips the current iteration and moves to the next one.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
}
// Output: 1, 2, 4, 5
π The loop skips i = 3
but continues with the next numbers.
for
→ When iterations are known.while
→ When condition controls execution.do...while
→ Executes at least once.for...in
→ Loops over object properties.for...of
→ Loops over array values.break
& continue
control loop flow.
@asadmukhtar