Open In App
Related Articles

JavaScript Loops

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

JavaScript Loops are powerful tools for performing repetitive tasks efficiently. Loops in JavaScript execute a block of code again and again while the condition is true.

For example, suppose we want to print “Hello World” 5 times. This can be done using JS Loop easily. In Loop, the statement needs to be written only once and the loop will be executed 5 times as shown below:

JavaScript

for (let i = 0; i < 5; i++) {
    console.log("Hello World!");
}

                    

Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
 

JavaScript for Loop

The JS for loop provides a concise way of writing the loop structure. The for loop contains initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. 

Syntax

for (initialization; testing condition; increment/decrement) {
    statement(s)
}

Flowchart

  • Initialization condition: It initializes the variable and mark the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
  • Test Condition: It is used for testing the exit condition of a for loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
  • Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.
  • Increment/ Decrement: It is used for updating the variable for the next iteration.
  • Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.

Example

Javascript

// JavaScript program to illustrate for loop
let x;
  
// for loop begins when x = 2
// and runs till x <= 4
for (x = 2; x <= 4; x++) {
    console.log("Value of x: " + x);
}

                    

Output
Value of x: 2
Value of x: 3
Value of x: 4

JavaScript while Loop

The JS while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. 

Syntax

while (boolean condition) {
    loop statements...
}

Flowchart

while loop

  • While loop starts with checking the condition. If it is evaluated to be true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason, it is also called the Entry control loop
  • Once the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an updated value for the variable being processed for the next iteration.
  • When the condition becomes false, the loop terminates which marks the end of its life cycle.

Example

Javascript

// JavaScript code to use while loop
let val = 1;
  
while (val < 6) {
    console.log(val); 
    val += 1;
}

                    

Output
1
2
3
4
5

JavaScript do-while Loop

The JS do-while loop is similar to the while loop with the only difference is that it checks for the condition after executing the statements, and therefore is an example of an Exit Control Loop. It executes loop content at least once event the condition is false.

Syntax

do {
    Statements...
}
while (condition);

Flowchartdo-while

  • The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.
  • After the execution of the statements and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts.
  • When the condition becomes false, the loop terminates which marks the end of its life cycle.
  • It is important to note that the do-while loop will execute its statements at least once before any condition is checked and therefore is an example of the exit control loop.

Example

Javascript

let test = 1;
  
do {
    console.log(test);
    test++;
} while(test <= 5)

                    

Output
1
2
3
4
5

JavaScript for-in Loop

JS for-in loop is used to iterate over the properties of an object. The for-in loop iterates only over those keys of an object which have their enumerable property set to “true”.

Syntax

for(let variable_name in object_name) {
    // Statement
}

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

Javascript

let myObj = { x: 1, y: 2, z: 3 };
for (let key in myObj) {
    console.log(key, myObj[key]);
}

                    

Output
x 1
y 2
z 3

JavaScript for-of Loop

JS for-of loop is used to iterate the iterable objects for example – array, object, set and map. It directly iterate the value of the given iterable object and has more concise syntax than for loop.

Syntax:

for(let variable_name of  object_name) {
    // Statement
}

Example: This example shows the use of for-of loop.

Javascript

let arr = [1, 2, 3, 4, 5];
for (let value of arr) {
    console.log(value);
}

                    

Output
1
2
3
4
5

JavaScript Labeled Statement

JS label keyword does not include a goto keyword. Users can use the continue keyword with the label statement. Furthermore, users can use the break keyword to terminate the loop/block. You can also use the break keyword without defining the label but it terminates only the parent loop/block. To terminate the outer loop from the inner loop using the break keyword, users need to define the label.

Syntax

Label:
    statement (loop or block of code)

Example

Javascript

let sum = 0, a = 1; 
  
// Label for outer loop 
outerloop: while (true) { 
    a = 1; 
  
    // Label for inner loop 
    innerloop: while (a < 3) { 
        sum += a; 
        if (sum > 12) { 
  
            // Break outer loop from inner loop 
            break outerloop; 
        
        console.log("sum = " + sum); 
        a++; 
    
}

                    

Output
sum = 1
sum = 3
sum = 4
sum = 6
sum = 7
sum = 9
sum = 10
sum = 12

JavaScript Break Statement

JS break statement is used to terminate the execution of the loop or switch statement when the condition is true.

Syntax

break;

Example

Javascript

for (let i = 1; i < 6; i++) {
    if (i == 4) 
        break;
          
    console.log(i);
}

                    

Output
1
2
3

JavaScript Continue Statement

JS continue statement is used to break the iteration of the loop and follow with the next iteration. The break in iteration is possible only when the specified condition going to occur. The major difference between the continue and break statement is that the break statement breaks out of the loop completely while continue is used to break one statement and iterate to the next statement.

Syntax

continue;

Example

Javascript

for (let i = 0; i < 11; i++) {
    if (i % 2 == 0) 
        continue;
          
    console.log(i);
}

                    

Output
1
3
5
7
9

JavaScript Infinite Loop (Loop Error)

One of the most common mistakes while implementing any sort of loop is that it may not ever exit, i.e. the loop runs for infinite times. This happens when the condition fails for some reason. 

Example: This example shows an infinite loop.

Javascript

// JavaScript program to illustrate infinite loop
  
// Infinite loop because condition is not false
// condition should have been i>0.
for (let i = 5; i != 0; i -= 2) {
    console.log(i);
}
  
let x = 5;
  
// Infinite loop because update statement
// is not provided
while (x == 5) {
    console.log("In the loop");
}

                    




Last Updated : 31 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads