Javascript Loops

Loops in javascript

Loops in javascript

Loops allow us to execute a set of statements repeatedly until the specified condition is met.

In javascript we have 2 types of loops

  1. for loop
  2. while loop

for loop syntax

for (intialization; condition; updation) {
  // code block to be executed
}
- intialization: we intialize the required variables - condtion: To check whether to run the statements in the forloop block or not - updation: To update the intialized variable to make the condition invalid/valid based on the requirement.

for loop example 1

for (var i = 0; i < 5; i++)
{
    console.log(i);
}

It will give below output

0 1 2 3 4
  • In the above code we initialized i to 0 and checked condition i < 5 and updated i value by one in each iteration.
  • Above iterates 5 times and executes the code and for the 6th iteration the condition fails so, it stops the execution.

while loop syntax

JavaScript includes while loop to execute code repeatedly till it satisfies a specified condition. Unlike for loop, while loop only requires condition expression.

while(condition)
{
    /* code to be executed till the specified condition is true */
}

while loop example

var i =0;

while(i < 5)
{
    console.log(i);
    i++;
}

It will give below output

0 1 2 3 4

We use keyword break statement to stop the execution of the loop and continue to skip the iteration. Let's see a few examples.

for (var i = 0; i < 5; i++)
{
    if(i == 3){
        continue;
    }
    console.log(i);
}

It will give below output

0 1 2  4
for (var i = 0; i < 5; i++)
{
    if(i == 3){
        break;
    }
    console.log(i);
}

It will give below output

0 1 2

Let's see the same in while loop

var i =0;

while(i < 5)
{
    if(i == 3){
        break;
    }
    console.log(i);
    i++;
}

It will give below output

0 1 2
var i =0;

while(i < 5)
{
    if(i == 3){
        continue;
    }
    console.log(i);
    i++;
}

It will give below output

0 1 2 4