Skip to main content

Command Palette

Search for a command to run...

"Loops" in JavaScript

Updated
2 min readView as Markdown
"Loops"  in  JavaScript

The loop is a programming way to run a set of code repeatedly until a certain condition is true.

Different Kinds of Loops

  • for loop

  • while loop

  • do/while loop

  • for/of loop

  • for/in loop

    For Loop

    For loop allows to iteration of a block of code and a specific number of code.

    The for statement creates a loop with 3 expressions:

    *Expression 1 - is executed (one time) before the execution of the code block.

    *Expression 2 - defines the condition for executing the code block.

    *Expression 3 - is executed (every time) after the code block has been executed.

    syntax:

      for (let expression1; expression2; expression3){
          // code block to be executed
    
       }
    

    Example:

  •                 for (let n=2; n<=10; n = n + 2 ){
                        console.log(n)
                     }
    
                    //here terminal
                    2
                    4
                    6
                    8
                    10
    
  • While Loop

While loop executes a block of code while a certain condition is true.

Syntax:

while(condition){
      // code block to be executed
}

Example:

let b = 0;

while(b<=10){
         console.log(b)
         b = b + 3
}
// here terminal
0
3
6
9

Do/While Loop

Do/while loop is similar to a while loop, except that the block of code executes at-least once, even if the condition is false.

Syntax:

do{
    //code block to be executed
}
while(condition);

Example:

let n = 0;

do{
console.log(n);
n++
}while(n > 10);

//here terminal
0

For Of Loop

For...of loop is used to loop through the values of arrays & strings, it allows access directly to values.

Syntax:

for ( variable of array){
       //code block to be executed

}

Example:

for (n of "name"){
       console.log(n)
}
// here terminal
n
a
m
e

For In Loop

For..in loop is used to loop through the properties of an object, it allows access values associated with those keys

Syntax:

 for (key(any name can give) in object){
        //code to be executed

 }

Example:

let employee = {
    name : "X",
    title: "XY",
    roll : 99
}

for( x in employee){
       console.log(employee[x])

 }

//here terminal
x
xy
99

More from this blog