JavaScript Loops
Loops are an important concept in JavaScript. They are used to repeat a block of code multiple times until a specific condition is met.For example, instead of writing the same code 5 times, we can use a loop to execute it 5 times.
Why Do We Use Loops?
- Reduce repeated code
- Save time
- Work with arrays and objects
- Perform the same task multiple times
- Make programs easier to maintain
Types of Loops in JavaScript
JavaScript provides several types of loops:
-
forloop -
whileloop do...whileloopFor Loop
The for loop is commonly used when we know how many times we want to repeat something.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
Here:
-
let i = 1→ starting value -
i <= 5→ condition -
i++→ increases the value by 1
2. While Loop
The while loop runs as long as the condition is true.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
The loop stops when i becomes greater than 5.
3. Do...While Loop
The do...while loop executes the code at least once, even if the condition is false.
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
The code inside do runs first, and then JavaScript checks the condition.
Conclusion
JavaScript loops make it easy to repeat tasks without writing the same code again and again.The for loop is useful when you know the number of repetitions, while while and do...while are useful when the repetition depends on a condition.
Top comments (0)