What is a Loop?
A loop repeats a set of instructions until a condition is met.
Example:
Instead of writing console.log("Hello") 5 times, we can use a loop.
Types of Loops in JavaScript
JavaScript provides several types of loops:
- for loop
- while loop
- do...while loop
- for...of loop(To be discussed)
- for...in loop
1. for loop:
- for loop is used to execute a block of code repeatedly, until a specified condition evaluates to false.
for (initialization; condition; increment/decrement) {
// code to execute
}
Best used when you know how many times to loop.
for (let i = 1; i <= 5; i++) {
console.log("Hello " + i);
}
O/P:
Hello 1
Hello 2
Hello 3
Hello 4
Hello 5
2. while Loop:
The while loop runs as long as the condition is true.
while (condition) {
// code
}
Used when the number of iterations is not fixed.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
O/P:
1
2
3
4
5
3. do...while Loop:
This loop runs at least once, even if the condition is false.
do {
// code
} while (condition);
Useful when the code must run at least once.
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
4. for...of Loop:
Used to iterate over the values of arrays or strings.
Best for arrays and iterable objects.
let fruits = ["apple", "banana", "mango"];
for (let fruit of fruits) {
console.log(fruit);
}
O/P:
apple
banana
mango
5. for...in Loop:
Used to iterate over keys (properties) of an object.
Best for objects.
let person = {
name: "Anees",
age: 30
};
for (let key in person) {
console.log(key + ": " + person[key]);
}
O/P:
name: Anees
age: 30
Important Keywords:
- break
- continue
break: Stops the loop completely.
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
console.log(i);
}
O/P:
1
2
continue: Skips the current iteration.
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
console.log(i);
}
O/P:
1
2
4
5
Advantages of Loops
- Saves time and reduces code duplication
- Makes code cleaner and readable
- Handles repetitive tasks easily
- Useful in arrays, objects, and automation
Top comments (0)