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.
3) DO...WHILE LOOP
Similar to while, but runs at least once (even if condition is false)
let i = 6;
do {
console.log(i);
i++;
} while (i <= 5);
Output:
7
Code must run at least once in do-while loop
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 = 1; i <= 5; i ++) {
console.log(i*3);
}
Output:
3
6
9
12
15
5) Multiples of 3 and 5
<!DOCTYPE html>
<html>
<head>
<title>document</title>
</head>
<body>
<script>
for(let i=1;i<=30;i++){
if(i%3===0 && i%5===0){
document.write("Multiples of 3 and 5:"+i+ "<br>");
}
}
</script>
</body>
</html>
Output:
Multiples of 3 and 5:15
Multiples of 3 and 5:30
6) Multiples of 3 or 5
<!DOCTYPE html>
<html>
<head>
<title>document</title>
</head>
<body>
<script>
for(let i=1;i<=30;i++){
if(i%3===0 || i%5===0){
document.write(i+"<br>");
}
}
</script>
</body>
</html>
Output:
3
5
6
9
10
12
15
18
20
21
24
25
27
30
7) Divisors of given number
<!DOCTYPE html>
<html>
<head>
<title>document</title>
</head>
<body>
<script>
let num=10;
for(let i=1;i<=num;i++){
if(num%i==0){
document.write(i+" ");
}
}
</script>
</body>
</html>
Output:
1 2 5 10
8) Count of Divisors of given number
<!DOCTYPE html>
<html>
<head>
<title>document</title>
</head>
<body>
<script>
let num=10;
let count=0;
for(let i=1;i<=num;i++){
if(num%i==0){
document.write(Divisors of 10:+" ");
count++
}
}
document.write("<br>");
document.write("Count:"+count);
</script>
</body>
</html>
Output:
Divisors of 10:1 2 5 10
Count:4
Top comments (0)