ES6

5 DIFFERENT ES6 LOOPS

es6-loops

es6-loops

for loop

for loop repeats as long as the condition is true and stops only when the condition evaluates to false. This is similar to for loops in Java or C++.

Syntax:

for ([initialExpression]; [condition]; [incrementExpression]){
  code block to be executed
}

Example: Below we are using for loop to print numbers 0 to 4

forEach loop

forEach is a method which is present in each array. When forEach is executed over an array it calls a callback function for each item in the array.

Syntax:

array.forEach(function(currentValue, index, arr), thisValue)

Example: Below example shows an array of fruits and we use forEach to iterate over the items of the array.

for…in loops

for…in loop makes our task of looping an object easy, it iterates over each property of an object.

Syntax:

for (variable in iterable) {
  code block to be executed
}

Example: Below we are using for…in loop to iterate over the school object and printing each property with its value.

for…of loop

The for…of statement creates a loop Iterating over iterable objects like Array, Map, Set and even strings.

Syntax:

for (variable of iterable) {
  code block to be executed
}

Example: Below example showcase how we use for…of loop to iterate over an array of emoji fruits and then iterating over each character of a string.

while loop

A while loop works similar to for loop i.e. it keeps executing the statement repeatedly until the condition becomes false.

Syntax:

while (condition) {
  code block to be executed
}

Example: Below example shows looping from 1 to 10 using while syntax.

do…while loop

Unlike while loop, do…while loop executes it’s statement first and then checks the condition, if the condition is true then it continues to repeat else it breaks the execution.

Syntax:

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

Example: Below example again shows printing numbers 1 to 10 but using do…while syntax this time.

Let me know your thoughts