JavaScript Loops (For, While, Do-While, For...of, For...in)

Introduction

In JavaScript, a loop serves as a programming construct that enables the execution of a specific sequence of instructions multiple times. Loops are instrumental in minimizing redundancy, as they allow a block of code to be executed repeatedly while a defined condition remains true.

In JavaScript, loops contribute to more streamlined and efficient code. They enable the repetition of a specific block of code through various types such as for, while, do-while, or for-in loops.

Types of Loops in JavaScript

There are several types of loops present in JavaScript. Such as:

  • JavaScript for Loop
  • JavaScript while Loop
  • JavaScript do-while Loop
  • JavaScript for…of Loop
  • JavaScript for…in Loop
  • JavaScript for Loop

The JavaScript for loop serves as a control flow construct that enables the execution of code multiple times depending on a specified condition. This loop encompasses initialization, a condition to evaluate, and an increment or decrement operation, all consolidated into a single line.

Syntax

The syntax of the for loop is as follows:

Example

for(initialization; condition; increment/decrement){

//code

}

Example

Example

for(let i= 1; i<=5; i++){

    console.log("Example");

}

Output:

Output

Example

Example

Example

Example

Example

Explanation

In this example

Initializes the counter variable (let i = 1).

Tests the condition(i <=5); runs while true.

Carries out the operations within the loop's body and subsequently increases the counter (i++).

JavaScript while Loop

In JavaScript, the while loop establishes a repetition structure that executes as long as a defined condition remains true. The JavaScript while loop persists in running until the condition is assessed to be false.

Within a while loop, the condition is established prior to the execution of the loop. Typically, a variable is either incremented or modified within the body of the while loop, which helps to ascertain the point at which the loop should terminate.

Syntax

The syntax of while loops is as follows:

Example

while(condition){

    //code block to be executed

}

Example

Example

let a = 0;

while(a <= 3){

    console.log("Welcome to our tutorialech");

    a++;

}

Output:

Output

Welcome to our tutorialech

Welcome to our tutorialech

Welcome to our tutorialech

Welcome to our tutorialech

Explanation

In this illustration, the while loop will continue to execute as long as the condition a <= 3 remains valid. Given that a begins at 0 and increases by 1 with each iteration, the loop will execute a total of 4 times (for the values 0, 1, 2, and 3). Upon completing the 4th iteration, a will have a value of 4, which renders the condition a <= 3 false, resulting in the termination of the loop.

JavaScript do-while Loop

The "do while" loop in JavaScript is a control structure that facilitates the execution of a block of code a single time before evaluating a specified condition. Following the initial execution, the loop continues to repeat as long as the condition evaluates to true.

In JavaScript, do-while loops are particularly useful in scenarios where the execution of the loop body is required to occur at least one time. The termination of these loops takes place when the specified condition evaluates to false.

Syntax

The syntax of the do-while loop is as follows:

Example

do{

//code to execute

}while(condition)

Example

Example

let p = 1;

let q = 1;

do{

    p = p + q;

    console.log(p);

    q++;

}while(q<5)

Output:

Output

2

4

7

11

Explanation

In this illustration, we begin by setting both p and q to 1. The loop initiates, and p is recalculated to p + q, resulting in 1 + 1, which equals 2. The output from console.log(p) displays 2, and subsequently, q is increased to 2. The condition of the loop, q < 5, evaluates to true; therefore, the loop will continue to execute until q is no longer less than 5.

JavaScript for…of loop

In JavaScript, the for…of loop iterates over an object's values rather than their keys. With the help of this you can directly access the items as opposed to index-reference. Some of the iterable objects are as follows:

  • An array of elements.
  • A string of characters.
  • A map of key/value pairs.

Syntax

The syntax of for…of loop is as follows:

Example

for(variable of iterable){

    //code to execute

}

Example

Example

const items = ['BMW', 'Ferrari', 'Mustang'];

for(const item of items){

    console.log(item);

}

Output:

Output

BMW

Ferrari

Mustang

JavaScript for…in Loop

In JavaScript, the for…in loop serves the purpose of traversing the properties within an object. It exclusively loops through the keys of an object that possess their enumerable attribute configured to "true."

Syntax

The syntax of for…in loop is as follows:

Example

for(key in object){

//code to execute

}

Example

Example

const items = {Phone: 2, Laptop: 1, TV: 1};

for(const Appliance in items){

    console.log(Appliance);

}

Output:

Output

Phone

Laptop

TV

And if you want to access the values:

Output:

Output

2

1

1

How to Choose the Right Loop?

In JavaScript, loops are handy if you want to run the same code repeatedly, each time with different values. You can choose the right loop based on:

  • When the number of iterations is known, then use the for loop.
  • When the condition depends on dynamic factors, use the while loop.
  • When you ensure the block executes at least once, use the do-while loop.
  • When you want to iterate over object properties, use the for…in loop.
  • When you want to iterate through an iterable object, use the for…of loop.
  • Conclusion

To summarize, JavaScript offers a variety of loop constructs, as demonstrated in the preceding discussion, that allow for iterating through a data collection or executing a block of code a defined number of times. The types of objects that can be iterated include arrays, strings, maps, and additional object types.

Input Required

This code uses input(). Please provide values below: