Looping Statements in JavaScript
Looping statements in JavaScript are used to repeat a block of code multiple times until a condition becomes false. Instead of writing the same code again and again, loops help make the code shorter and easier to manage.
JavaScript mainly provides the following loops:
1) for Loop
The for loop is used when we know how many times the loop should run.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
Here, the loop starts from 1 and runs until 5.
2) while Loop
The while loop runs as long as the given condition is true.
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
This also prints numbers from 1 to 5.
Example Programs:
Looping Programs in JavaScript
1) 1 1 1 1 1
Print the number 1 five times.
for (let i = 1; i <= 5; i++) {
console.log(1);
}
Output:
1
1
1
1
1
2) 1 2 3 4 5
Print numbers from 1 to 5.
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1
2
3
4
5
3) 1 3 5 7 9
Print the first five odd numbers.
for (let i = 1; i <= 9; i += 2) {
console.log(i);
}
Output:
1
3
5
7
9
4) 3 6 9 12 15
Print multiples of 3.
for (let i = 3; i <= 15; i += 3) {
console.log(i);
}
Output:
3
6
9
12
15
Conclusion
Loops are very useful in JavaScript for performing repetitive tasks such as printing numbers, iterating through arrays, and processing data efficiently.
Top comments (0)