Open In App

How to write a for loop in ES6 ?

Last Updated : 14 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Loops are the way to do the same task again and again in a cyclic way. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed an iteration.

There are mainly two types of loops:

Entry Controlled loops: In this type of loop the test condition is tested before entering the loop body. For Loop and While Loop is entry-controlled loops.

Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. do – while loop is exit controlled loop.

Here in this article, we will learn about different types of for loops.

There are 3 types of For in ES6:

1. for( ; ; ): The for loop executes the code block for a specified number of times.

Syntax:

for( Initialization; Terminate Condition; Increment/Decrement )

The Initialization can also be known as the count value as this variable keeps track of the counting till the terminator. Increment/Decrement the variable to a certain value of steps. The terminate condition determines the indefinite or definite category, because if the terminator statement is valid then the loop gets terminated at a definite time, else it goes for infinity loops and will be an indefinite loop.

Example: This example shows the use of the for loop

Javascript




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


Output:

10

2. for…in: The for…in loop is used to loop through an object’s properties.

Syntax:

for(variable_name in object) {  
   ...  
}

In each iteration, one property from the object is assigned to the variable_name and this loop continues till the end of the object properties. It certainly ends its iteration for sure so, it comes under the definite loop.

Example: This example shows the use of the for…in loop.

Javascript




const numbers = [45, 4, 9, 16, 25];
 
let val = 0;
for (let x in numbers) {
    val += numbers[x];
}
console.log(val)


Output:

99

3. for…of: The for…of loop is used to execute the loop block to iterate the iterable instead of object literals.

Syntax:

for(variable_name of object) {  
   ...
}

Example: This example shows the use of the for…of loop

Javascript




const geek = ["Geeks", "For", "Geeks"];
 
let text = "";
for (let x of geek) {
    text += x + "<br>";
}
console.log(text)


Output:

Geeks
For
Geeks


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads