Looping statements in the programming languages help to execute the set of instructions/functions repeatedly while a condition evaluates to true. Loops are an ideal way to perform the execution of certain conditions repeatedly. In a loop, the repetition is termed as iteration.
You can see the classification of loops in the following figure:
Let us try to understand the loops in the above image.
A definite loop has a definite/fixed number of iterations. In ES6, there are three types of definite loops that are listed below:
Definite Loop | Description |
---|---|
for( ; ; ) Loop | It executes the block of code for a definite number of times. |
for…in Loop | It iterates through the properties of the object. |
for…of loop | Unlike object literals, it iterates the iterables (arrays, string, etc.). |
Let us try to elaborate on the above loops.
The for ( ; ; ) loop is used to iterate a part of the program multiple times. If you have a fixed number of iterations, then it is always recommended to use 'for' loop.
for(initialization;condition;incr/decr){ //statement or code to be executed }
The 'for' loop includes some parts that are defined as follows:
Flowchart
In the following, there are three examples of 'for' loop in which we are showing the simple 'for' loop, 'for' loop having multiple expressions and infinite 'for' loop.
The table of 2 by using for loop.
var i; for(i=1;i<=10;i++) { console.log("2 x "+ i +" =", 2*i); }
"use strict" for(let temp, a = 0, b = 1; b<40; temp = a, a = b, b = a + temp) console.log(b);
for(;;) { console.log("infinitive loop"); // It will print infinite times }
For terminating it, you can use ctrl + c.
The for…in loop is similar to for loop, which iterates through the properties of an object, i.e., when you require to visit the properties or keys of the object, then you can use for…in loop. It is a better choice when you are working with objects or dictionaries where the order of index is not essential.
for (variable_name in object_name) //Here in is the keyword { // statement or block to execute }
In every iteration, one property from the object is assigned to the name of the variable, and this loop continues till all of the object properties get covered.
function Mobile(model_no){ this.Model = model_no; this.Color = 'White'; this.RAM = '4GB'; } var Samsung = new Mobile("Galaxy"); for(var props in Samsung) { console.log(props+ " : " +Samsung[props]); }
If you pass the function in the properties of the object then this loop will give you the complete function in the output. You can it's illustration in the following code:
function Mobile(model_no){ this.Model = model_no; this.Color = 'White'; this.RAM = '4GB'; this.Price = function price() // The loop will give you this function as it is written here. { console.log(this.model + "Price = Rs. 3300"); } } var Samsung = new Mobile("Galaxy"); for(var props in Samsung) { console.log(props+ " : " +Samsung[props]); }
So, you can also visit the methods by using the for…in loop.
Unlike the object literals, this loop is used to iterate the iterables (arrays, string, etc.).
for(variable_name of object_name) // Here of is a keyword { //statement or block to execute }
In every iteration, one property from the iterables gets assigned to the variable_name, and the loop continues till the end of the iteration.
var fruits = ['Apple', 'Banana', 'Mango', 'Orange']; for(let value of fruits) { console.log(value); } /* You can also write the above code like: for(let value of ['Apple', 'Banana', 'Mango', 'Orange']) { console.log(value); } */
An indefinite loop has infinite iterations. It is used when the number of iterations within the loop is intermediate or unknown.
There are two types of indefinite loops that are listed below:
Indefinite Loops | Description |
---|---|
while Loop | It executes the instructions each time till the defined condition evaluates to true. |
do…while Loop | It is similar to the while loop, but the key difference is that the do…while loop executes the loop at once irrespective of the terminator condition. |
Let us try to elaborate on the above loops.
A while loop is a control flow statement that allows the repeated execution of code based on the given Boolean condition. It consists of a block of code and an expression/condition.
The while loop checks the expression/condition before the execution of block; that's why this control structure is often known as a pre-test loop.
while (condition) { statements; }
Flowchart
var y = 0; while (y < 4) { console.log(y); y++; }
It is a control flow statement that executes a block of code at least once, and then it will depend upon the condition whether or not the loop executes the block repeatedly.
The do..while loop checks the condition after the execution of the block, that's why this control structure is also known as the post-test loop. It is also possible that the condition always evaluates to true, which will create an infinite loop.
do { // block of statements to be executed; } while (expression);
var count = 6, fact = 1; do { fact = fact * count--; } while (count > 0); console.log(fact);
If you perform this example by using the while loop, then this will be written as:
var count = 6, fact = 1; while (count > 0) { fact = fact * count--; } console.log(fact);
The key difference between the above two examples is that the while loop is entered only if the condition passed to it will evaluate to true. But the do…while loop executes the statement once, it happens because of the starting iteration of the do…while loop does not consider as the Boolean expression. Then for the further iterations, the while will check the condition and takes the control out from the loop.
The loop control statements are used for interrupting or control the flow of the execution. These statements change the execution from its normal sequence. JavaScript provides you the full control to handle the loops and switch statements.
There may be some circumstances when you require to come out from the loop without reaching its bottom. There may also be some situations when you need to skip the part of the code and start the further iterations of the loop. So, for handling such situations in JavaScript, we have a break and continue statements.
Loop control statements | Description |
---|---|
The break statement | The break statement is used to bring the control of the program out from the loop. |
The continue statement | It skips the subsequent statements of the current iteration and brings control of the program to the beginning of the loop. |
Let us try to elaborate on the above control statements.
It is used to take control of the program out from the loop. You can use the break statements within the loops or in the switch statements. Using a break statement within the loop causes the program to exit from the loop.
break;
var n = 1; while(n<=7) { console.log("n="+n); if(n==4) { break; } n++; }
The above code will print the four values of n for the range of numbers within 1 to 7.
When the value of n is 4, then the loop forces the control to exit the loop because of the break statement. You will get the following output after the successful execution of the above code.
Unlike the break statement, the continue statement does not exit from the loop. It terminates the current iteration of the loop and starts the next iteration.
continue;
var n = 0; while(n<=5) { n++; if(n==3) { continue; } console.log("n = "+n); }
The above example will display the values of n, but it will skip the current iteration if the value of n will be 3. You will get the following output after the successful execution of the above code.
A label is nothing but an identifier followed by a colon (:), and it applied on a block of code or a statement. You can use the label with a break and continue to control the flow.
You cannot use the line breaks in between the break and continue statement and its label name. Also, there should not be any statement in between the label name and an associated loop.
The syntax for defining the label
labelname: Statement
labelname: Any identifier of JavaScript, which is not a reserved word.
Statement: It is a JavaScript statement.
Label | Description |
---|---|
Label with the break statement | It is used to exit from the loop or from the switch statement without using a label reference, but with label reference, it is used to jump out from any code block. |
Label with continue statement | It is used to skip one iteration of the loop with or without using the label reference. |
Without using the label reference, you can use the break only to exit from the loop or from the switch, but by using the label reference, you can use the break to jump out from any code block.
break labelname;
var x, y; loop1: //The first for statement is labeled as "loop1." for (x = 1; x < 4; x++) { loop2: //The second for statement is labelled as "loop2" for (y = 1; y < 4; y++) { if (x === 2 && y === 2) { break loop1; } console.log('x = ' + x + ', y = ' + y); } }
The continue statement can only be used for skipping one loop iteration either with the label reference or without using the label reference.
continue labelname;
var x, y; loop1: //The first for statement is labelled as "loop1" for (x = 1; x < 4; x++) { loop2: //The second for statement is labelled as "loop2" for (y = 1; y < 4; y++) { if (x === 2 && y === 2) { continue loop1; } console.log('x = ' + x + ', y = ' + y); } }
You can notice in the following output of the above code that it skips both "x = 2, y = 2" and "x = 2, y = 3".
Before ECMAScript 6, the LabeledStatement specification didn't allow for the association of a label statement with a FunctionDeclaration. However, the labeled FunctionDeclaration was the allowable extension in non-strict code, and most of the browser-hosted implementations of ECMAScript supported that extension.
But in ECMAScript 2015 (ES6), the grammar productions for the LabeledStatement allow the use of FunctionDeclaration as a LabeledItem, but it includes an error rule that causes a syntax error if that occurs.
For the web browser compatibility, that rule is modified with the addition of underlined text:
LabeledItem : FunctionDeclaration
It will cause a syntax error if any of the source code of strict mode matches this rule.
Starting with ECMAScript 2015, the labelled function declarations standardized for non-strict code:
L: function hello() {}
If you write the above code in strict mode then this will throw a syntax error:
'use strict'; L: function hello() {} // SyntaxError: In strict mode code, functions can only be declared at top level or inside a block.
The Generator Functions can neither be labeled in non-strict mode nor in strict mode.
L: function* hello() { } // SyntaxError: Generator Functions cannot be labelled