What is Looping? And why do we use it?
Loops are used to execute a block of code repeatedly without writing the same code multiple times. They help reduce code repetition and make programs more efficient.
example:
without looping:
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
with looping:
for loop
Syntax
for(initialization; condition; increment){
// code
}
for(let i = 1; i <= 5; i++){
console.log(i);
}
This also gives me the same output, but the code is reduced to be smart.
output is:
1
2
3
4
5
Print Numbers from 5 to 1
for(let i = 5; i >= 1; i--){
console.log(i);
}
Explanation
i is initialized with 5.
The loop runs while i >= 1.
console.log(i) prints the current value of i.
i-- decreases the value by 1 after each iteration.
When i becomes 0, the condition 0 >= 1 is false, so the loop stops.
Output
5
4
3
2
1
Expected Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
program
for (let a = 1; a <= 10; a++) {
if (a % 3 == 0) {
console.log("Fizz");
}
else if (a % 5 == 0) {
console.log("Buzz");
}
else {
console.log(a);
}
}
Explanation
a is initialized with 1.
The loop runs while a <= 10.
If a is divisible by 3, it prints "Fizz".
Else if a is divisible by 5, it prints "Buzz".
Otherwise, it prints the number.
After each iteration, a++ increases the value by 1.
The loop stops when a becomes 11 because the condition 11 <= 10 is false.
output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
Print Odd Numbers Using continue
Expected Output
1
3
5
7
9
Program
for (let i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
console.log(i);
}
Explanation
i is initialized with 1.
The loop runs while i <= 10.
If i is an even number, continue skips the current iteration.
Only odd numbers reach console.log(i).
After each iteration, i++ increases the value by 1.
The loop stops when i becomes 11 because the condition 11 <= 10 is false.
Output
1
3
5
7
9
Expected Output
1
2
3
4
5
program
for (let i = 1; i <= 10; i++) {
if (i == 6) {
break;
}
console.log(i);
}
Explanation
i is initialized with 1.
The loop runs while i <= 10.
When i becomes 6, the break statement stops the loop immediately.
Since the loop stops before console.log(i), 6 is not printed.
The loop ends without checking the remaining values.
Output
1
2
3
4
5
Expected Output
1
3
program
for (let i = 1; i <= 5; i++) {
if (i === 2) {
continue;
}
if (i === 4) {
break;
}
console.log(i);
}
Explanation
i is initialized with 1.
The loop runs while i <= 5.
When i becomes 2, continue skips the current iteration, so 2 is not printed.
When i becomes 4, break stops the loop immediately, so 4 and the remaining values are not printed.
Only 1 and 3 are printed.
Output
1
3
Top comments (0)