Loops in ES6 | ECMAScript 6

Loops in ECMAScript 6

A Loop statement can be defined as a group of instructions that are always repeated. In the computer programming language, the loops help us to execute a collection of instructions that repeats again and again till the condition is true. In the loop statement, the repetition of a statement is defined as an iteration.

Classification of Loops

Loops in ECMAScript 6

Now, we are going to discuss each category of the loop in detail.

Definite Loops

This type of loop has a definite/ fixed/ constant number of iterations. There are the following three types of definite loops used in ECMAScript 6.

Loop             Description
             For (; ;) loop The for loop is used to execute the block code for a particular number of times within a termination condition.
             For…in loop The for…in loop is used to execute the block code by using the properties of an object.
             For…of loop The for…of loop is used to execute the iterables (string, array) instead of object literals.

Now, we are going to discuss each loop with syntax and example.

The For (; ; ) loop

The for loop helps us to execute the block code for a particular number of times. It means if we have a constant number of iterations, then we will use a for loop.

Syntax

For (initialization; conditions; increment/ decrement)
 {
          // code statement to be executed
 } 

The for (; ;) loop contains the following elements-

Initialization: It is a process to initialize the variables and also used for existing initialized variables. Initialization is optional to use.

Condition: It always executes to check the loop condition. It always returns True/False (Boolean value). It executes until the loop condition is false. In ECMAScript, it is optional to use.

Increment/ Decrement: It is used to increase or decrease the value of a variable by 1(+1 /-1). It is also optional to use.

Flowchart of for (; ;) loop

Loops in ECMAScript 6

There are some examples given below, which represents the various kind of for loop.

Example 1

Here is an example of a simple for loop.

Var a;
 For (a=1; a<=10; a++)
 {
     Console.log (“4 x ” + a + “ = ”, 4 * a );
 } 

Output

Loops in ECMAScript 6

Here, we will try to illustrate the code of for loop with multiple expressions.

Example 2

The below-given code helps us to understand the concept of for loop with multiple expressions.

“use strict”          // Directive for Strict mode
 For (let variable, p = 0, q = 1; q<100; variable = p, p = q, q = p + variable)
 {
             Console.log (q);
 } 

Output

After the execution of the above code, we will get the following output

Loops in ECMAScript 6

In the program code, we can easily merge the multiple expressions and assignments within a single loop by using comma (,).

Example 3

Here is an example of infinite for loop.

for (; ;)
 {
 Console.log (“Infinite loop”);          // this loop will run infinite time until we use break keyword
 } 

Output

Loops in ECMAScript 6

If we want to terminate this infinite loop then we will use Ctrl + C.

The For…in Loop

The for…in loop is similar to for loop, but it iterates the block code by using the properties of an object (The object keys). We can use a for…in loop when we are dealing with objects where the index order is not necessary.

In each iteration of the for…in loop, one property is allotted to the variable name. The loop executes the condition until the object have at least one property left. The for…in loop comes under the category of definite loops.

Syntax

for (variable_name in object)                  // in is used as a keyword      
 {      
             // Block code to be executed
 } 

Example

var employee = {“Emp_name” : “Daniel”, “Emp_id”: “D01”, “Emp_age” : 30}:
 for (var props in employee)
 {
   Console.log (props+ “ : ” + employee [props]);    
 } 

Output

After execution of the code, we will get the following output.

Loops in ECMAScript 6

If we pass a function as the properties of the object then we will get the whole function as the output. We will try to implement it with the following example.

function car = (model_no)
 {
      this. model =model_no;
      this. color = “Black”;
      this. transmission = “Manual”; 
      this. price = function price ()           // This function will return as the output 
 {
       Console.log (this. model + “price =500000”);
 }
 } 
 var Toyota = new car (“Fortuner”);
 for (var props in Toyota) 
 {
       Console.log (props+ “ : ” + Toyota[props]);
 } 

Output

After execution of the code, we will get the following output.

Loops in ECMAScript 6

In the code mentioned above, the function price () is returned as the output.

The For…of loop

The for…of loop is used to execute the iterables (array, string) instead of object literals.

In each iteration of for…of loop, one property is allotted to the variable name. The loop executes the condition until the object has at least one iteration left. The for…of loop comes under the category of definite loops.

Syntax

for (variable_name of the object)                  // of is used as a keyword      
 {      
             // Block code to be executed
 } 

Example

Var mobile = [‘Samsung’, ‘Micromax’, ‘Redmi’, ‘Nokia’];
 for (let value of mobile)
 {
          console.log (value);
 } 

Output

After the execution of the above example, we will get the following output.

Loops in ECMAScript 6

Indefinite Loop

The Indefinite loop has an unknown or transitional number of iterations inside the loop. In the Indefinite loop, we have an infinite number of iterations. There are following two types of indefinite loops listed below:

                      Loop                       Description
                While loop This loop is used to execute the condition until a particular condition is true. The condition classifies before the code statement is executed.
                 Do…while loop It is similar to a while loop, but the difference is; the do…while loop executes the code statement at one time without checking the condition.

Now, we are going to discuss each loop with syntax and example.

While Loop

The while loop is considered as a control statement. It is used to execute the program code in a repeated way based on the given Boolean condition. This loop is also known as “the pre-test loop.” In the while loop, we can check the condition before the execution of the block code.

The while loop contains; condition/ expression and block of code. The while loop comes under the category of Indefinite loop.

Syntax

while (condition/ expression)
 {
          //  Code or expression to be executed
 }  

Flowchart of While loop

Loops in ECMAScript 6

Example

Here, we discuss the example of while loop.

var r = 0; 
 while (r < 10)
 {
     console.log (r);
            r++; 
 }  

Output

After the successful execution of the example, we will get the following output.

Loops in ECMAScript 6

Note-          

  • When the condition is true, then the loop will be executed.
  • The condition/ expression is necessary to execute the loop.
  • If the condition is true, then the loop always executes, but if the condition is false, then the loop will terminate.

Do…while Loop

The Do…while loop is a control statement. It is used to execute the code block at least once before condition check; if the condition is true, then the loop executes continuously; otherwise, the loop will be terminated. The Do…while loop is also known as “the post-test loop”. This loop comes under the category of Indefinite loop.

Syntax

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

Flowchart of Do…while loop

Loops in ECMAScript 6

Example

Here, we discuss an example of Do…while loop.

let result = “”;
 let a = 0;
 do { 
      a = a + 1;
      result = result + a; 
 }  
 while (a < 10);
 console.log (result); 

Output

After the execution of the above code, we will get the following output.

Loops in ECMAScript 6

Difference between While and Do…while loop

                While Loop                    Do…while Loop
It checks the conditions before the execution. It checks condition after the execution.
It executes the code block if and only if the condition is true. It executes the code block at least once; even the condition is false later.
It is defined as an entry-controlled loop. It is defined as an exit-controlled loop.
We can use it when the condition is important. We can use it when the process is more important.
The semicolon (;) is not compulsory after the end of the while loop.                  The semicolon (;) is compulsory after the end of the do…while loop.                  
Syntax              while (condition) {               // statement }       Syntax               do {                         // statement } while (condition)         

Related Topics

Class in ES6

Class in ES6: The Class is a basic term in object-oriented programming (OOPs). A class helps to determine the prototype for modeling in real-world objects. It is used to formulate...

4 minutes read.

Loop Control Statement in ES6

Loop Control Statement in ECMAScript 6 The loop control statements can be defined as a set of conditions that control the execution of the loop. It executes the loop until the condition becomes false....

6 minutes read.

Object Destructuring in ES6

Object Destructuring in ES6 The term destructuring is referred to as the breakdown of the complex entities into simpler parts. It works like array destructuring. In the array destructuring, the values...

3 minutes read.

String in ES6

String in ES6 The term string can be defined as an object used to represent the sequence of the characters. The string is widely used to store a text-based value like...

9 minutes read.

Object in ES6

Object in ES6 The term object can be defined as an instance that contains the group of key-value pairs. We can modify it using the life cycle of an object in...

6 minutes read.

Validation in ES6

Validation in ES6 The term validation can be defined as a mechanism to check the information given by the user is correct or not according to the requirements. If the data...

9 minutes read.

Loops in ES6 | ECMAScript 6

Loops in ECMAScript 6 A Loop statement can be defined as a group of instructions that are always repeated. In the computer programming language, the loops help us to execute a collection of instructions...

8 minutes read.

Generator in ES6 | ECMAScript 6

ECMAScript 6 recommends a new way of working with iterators and functions. The way is named as generator or generator function. The ES 6 generator is a distinct type of function that...

5 minutes read.

Map Object in ES 6

Map Object in ES 6 ES 6 introduced a new feature that is included in JavaScript. In the previous versions of ECMAScript, if we want to perform mapping on values and...

5 minutes read.

Functions in ES6 | ECMAScript 6

Functions in ECMAScript 6 In ECMAScript programming language, the term ‘function’ can be defined as a collection or group of input statements, used to perform particular computational calculations and generate the output...

9 minutes read.

Types of Inheritance in ES6

Types of Inheritance The term inheritance can be divided into following three parts- Single-level InheritanceMultiple InheritanceMulti-level Inheritance Single-level Inheritance The single-level inheritance can be defined as an inheritance in which the child class can...

5 minutes read.

Module in ES6

Module in ES6 In ES6, the modules can be defined as a small chunk of program code stored in a file. The modules are used to modularize the source code with...

6 minutes read.

Variables in ES6 | ECMAScript 6

Variables in ECMAScript 6 A Variable is a place in memory used to store a value. There are some rules for declaration of the variable- Variable Initialization Initialization is a process of locating and storing the initial...

4 minutes read.

Arrow Function in ES6

Arrow Function in ES6  An Arrow function is a new concept recommended in ECMAScript 2015. It is also called “Fat Arrow Function.” It helps us to write the function more accurately. This function...

5 minutes read.

Dialog box in ES6

Dialog box in ES6 A dialog box can be defined as a regular type of window in the Graphical User Interface (GUI) of the operating system. It is also spelled as...

5 minutes read.

Events in ES6

Events in ES6 The events can be defined as the actions or the occurrence of an action that is perceived by the software. The event is used to handle the interaction between...

14 minutes read.

Array in ES6

Array in ES6 The array can be defined as an object that is used to display the set of homogenous type of elements in ECMAScript 6. The array provides the facility to store...

5 minutes read.

Features of ES6 | ECMAScript 6

The ES6 or ECMAScript 2015 came with various exiting and new features. These features make it a more robust and updated programming language than ES5. Some of these new promising features are Const...

6 minutes read.

Template Literals in ES6

Template Literals in ES6            ES6 introduced a new feature called template literals. It facilitates us to define a multiline string and executes the string interpolation. The template literals are referred to...

3 minutes read.

Environment Set up in ES6

Environment Set up in ES6 JavaScript is a portable language. It can execute on any browser or any host, and any operating system. Before the use of JavaScript, we need to...

5 minutes read.