for loop in javascript


Published on: July 03, 2021 By T.Andrew Rayan

for loop:

The 'for' loop in javascript is used to execute a block of codes repeatedly again and again until a particular condition is satisfied.

Syntax for the for loop:

for(initialization; condition; increment/decrement){
 // block of codes.
}

The intialization statement is executed only once during the first execution in the for loop.

The condition is checked to execute the block of codes. If condition is not satisfied then it will stop executing the loop. The increment or decrement statement is used to increment or decrement any value, usually the variable initialized in the initialization statement.

Example for the for loop:

This will print the value from 1 to 10 to the console. The first block in 'for' loop is initialization. This happens only once. Next we check the condition whether the value of 'i' is less than or equal to 10 if it satisfies then it prints the value of 'i' to the console.

Next time when executing the loop the value of 'i' is incremented because of the 3rd statement 'i++'. This continues until the condition gets false.

For loop can also be used to loop through the objects properties and the arrays using 'for/of' and 'for/in' loops.

for/in loop:

The 'for/in' loop is used to loop through the properties of the object.

Syntax for for/in loop:

for(let value in object){
  // block of codes.
}

Example for for/in loop:

Result

name is Andrew
age is 30

In the above example using for/in loop we loop through the employee object and display its property name and its value.

for/of loop:

The 'for/of' loop is used to loop through the array or any collections.

Syntax for the for/of loop:

for(let value in object){
  // block of codes.
}

Example for the for/of loop:

Output

Andrew
John

This will loop through the employees array and displays the name of the employee.


Most Read