DEV Community

Guna Ramesh
Guna Ramesh

Posted on

Looping in JS

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);
Enter fullscreen mode Exit fullscreen mode

with looping:
for loop
Syntax

for(initialization; condition; increment){
    // code
}
Enter fullscreen mode Exit fullscreen mode
for(let i = 1; i <= 5; i++){
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

This also gives me the same output, but the code is reduced to be smart.

output is:
1
2
3
4
5

Enter fullscreen mode Exit fullscreen mode

Print Numbers from 5 to 1

for(let i = 5; i >= 1; i--){
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Expected Output

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
Enter fullscreen mode Exit fullscreen mode

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);
    }
}

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Print Odd Numbers Using continue