DEV Community

Alaguselvan T
Alaguselvan T

Posted on

Looping statement in Javascript

Loops are used to execute a block of code repeatedly until a condition becomes false.
It will run until the condition is true and exit when the condition is false

1. for Loop
Used when you know the number of iterations.

Syntax

for (initialization; condition; increment/decrement) {
    // code
}
Enter fullscreen mode Exit fullscreen mode

Example:

for (let i = 1; i <= 5; i++) {
    console.log(i);//1 2 3 4 5
}
Enter fullscreen mode Exit fullscreen mode

2. while Loop
If we dont know the iteration count then use while loop
Checks the condition first. Executes as long as the condition is true.exit when is condition is false

Syntax:

while (condition) {
    // code
}
Enter fullscreen mode Exit fullscreen mode

Example:

let i = 1;

while (i <= 5) {
    console.log(i);//1 2 3 4 5
    i++;
}
Enter fullscreen mode Exit fullscreen mode

Difference Between for and while loop

Top comments (0)