Loops in JavaScript

Venish Sureliya
2 min readMay 7, 2022
Loops in JS

Loops in JavaScript are used to iterate a piece of code. In simple words, Loops are used to execute any block of code again and again until certain conditions are fulfilled.

There are major 3 types of loop in JavaScript, For loop, While loop and Do-While loop.

For Loop

In for loop, conditions are separated in three pieces using semicolon (;). The first condition line contains the initialization of variable / iterator used in for loop.

The second condition line contains stopping point information of loop where loop should not be executed anymore.

And the third condition line contains iteration statement which is supposed to update iterator value each time loop is executed.

Here we have iteration statement of increment.

for (let i = 0; i < 10; i++){
document.write(i + “<br>”);
}

While Loop

There are only a few changes in syntax of While loop than For loop. While in for loop, we were declaring and initializing value of iterator, stopping condition of loop and iteration statement, but we can neither declare and initialize variable, nor add iteration statement.

The only thing we are supposed to mention in while loop is loop stopping condition where execution of loop should be stopped.

let i = 0;
while (i < 10){
document.write(i + “<br>”);
i++;
}

Do-While Loop

In for and while loops, we were declaring the looping conditions before actual executable code but in Do-While loop, we are required to write executable code inside ‘Do’ and looping conditions are being written after ‘Do’.

Just like While loop, we cannot declare and initialize and mention iteration statement in ‘While’

let i = 0;
do{
document.write(i + “<br>”);
i++
} while(i < 10);

--

--