Loops in JavaScript | Loop Statement, Example

A loop in JavaScript is a statement block that repeatedly executes a statement or a series of statements, while a particular condition is true or until a specific condition becomes true.

In other words, loop statement is a control flow statement that executes a block of statements repeatedly until a termination condition met.

In brief, a loop statement executes the same block of statements repeatedly.

The block of statements can execute many times, from zero to infinite number depending on the requirement. Each execution of the loop is called iteration in JavaScript.

Let’s understand loops in JavaScript with the help of an example.

Suppose that we need to print the string “Hello world” a hundred times in a JavaScript program. It would be a tedious and boring task to write the following statement a hundred times:

// Writing the same statement 100 times like this will be a tedious and boring task.
    document.write("Hello world");
    document.write("Hello world");
    . . .
    . . .
   document.write("Hello world");

So, how will you resolve this problem?

To overcome this problem, JavaScript programming language provides a powerful feature called loop. This loop controls how many times a statement or a sequence of statements has to be executed in succession.

Using a loop statement in JavaScript program, we can simply tell JavaScript interpreter to print a statement hundred times instead of writing the code a hundred times to print the same statement.

The simple code to print a statement hundred times is:

let count = 0;
while (count < 100)
   document.write("Hello world");

Initially, the variable count set to 0. The loop checks whether count < 100 is true. If so, it executes the block or body of loop to print the message “Hello world” and increments count by 1.

It repeatedly executes the block of the loop until count < 100 becomes false. When count < 100 is false (i.e. when count reaches 100), the loop ends. After execution of loop statement, the control passes to the statement following the loop.
[adinserter block=”5″]
Thus, we can say that looping is a technique that executes the same lines of code repeatedly.

Loop Control Structure in JavaScript

A block of statements executes sequentially in the loop until a specific condition for the termination of the loop met. Therefore, a loop control structure comprises two parts:

  • Control statement
  • Body of the loop

The work of control statement is to evaluate (i.e. test) a certain condition and then perform the repeated execution of statements in the block of loop.

We can classify a control structure into two types depending on the position of control statement in the loop. They are:

  • Entry-controlled loop
  • Exit-controlled loop

The flowchart is shown in the below diagram.

JavaScript loops control structure

Entry-controlled loop: In the entry-controlled loop, the control conditions evaluate before the execution of block of the loop. If the specified conditions satisfy, then the body of loop will execute.

If not satisfied, then the body of loop will not execute. For example, while loop and for loop are entry-controlled loops.

Exit-controlled loop: In an exit-controlled loop, the specified conditions test at the end of the body of loop. Therefore, the body of loop executes unconditionally for the first time. For example, the do-while loop is an exit-controlled loop.
[adinserter block=”2″]
We must carefully declare the test conditions to perform the execution of the desired number of loops in JavaScript program.

Basic Steps to Process Loops in JavaScript

Basically, there are four steps to process loops in JavaScript that are:

  • Setting and initialization of a counter.
  • Execution of statements sequentially in the body/block of loop.
  • Evaluate for a specified condition for the execution of loop.
  • Incrementing the counter.

Types of Loops in JavaScript

JavaScript supports three types of loops that are as follows:

  • Simple loops
  • Nested loops
  • Infinite loops

We have already discussed simple loops in the above sections. Now, we will discuss nested loops in JavaScript.

Nested Loops in JavaScript

Like conditional statements, we can also nest a loop structure one inside the other. A loop placed inside another is called nested loops in JavaScript.

Nested loops allow us to loop over two variables. The outside loop is called outer loop, and the inside loop is called inner loop.

Each time the outer loop iterates, the inner loop iterates until its condition becomes false.

Consider the following simple example that shows a pair of nested for loops in JavaScript.

var x, y;
for(x = 1; x <= 5; x++)
    for(y = 1; y <= 5; y++)
   // statements to be executed.

In the above example, x and y are called loop variables because they control the execution of a loop. There are two for loops in the above example.

The first loop that uses x as its counter variable is outer loop. The second loop that uses y as its counter variable is inner loop.

Each loop will execute its corresponding statements 5 times. The outer loop will execute 1 to 5 only once.

But, the inner loop will iterate 5 times for each iteration of outer loop, and will execute the statements for each value of x and y through inner loop.

When the inner loop end, then the outer loop starts the next cycle.

Infinite Loop in JavaScript

An infinite loop in JavaScript is a loop statement that repeats forever. We also known it as endless loops because the specified condition is always true and the body of loop executes repeatedly, and never ends.

Consider the following example given below.

var n = 1;
while(n > 0)
     document.write(n, "<br>");
// n never changes.

In this example, the digit 1 will display an infinite number of times on the browser, or at least until you end the program. Let’s consider another example of infinite loop that runs the code forever.

// Initiating an infinite loop
   while (true) {
       // execute code forever

This is the easiest way to create an infinite loop because the value true is conditional and its condition will always be true.

Another classic example is for loop, where we will not define increment or decrement expression.

// Infinite loop because of no increment or decrement expression.
   for (var i = 1; i <= 10) {
        document.write(i * i, "<br>");

In this example, the increment or decrement expression is missing inside the for loop statement. As a result, there is no change in the value of variable i, resulting in an infinite loop.

Obviously, infinite loop must avoid by the programmer because they can be difficult to spot in a program. JavaScript does not show any error actually that tells you there is an infinite loop. Thus, you must be careful when you create a loop in any program.

Escaping from a Loop in JavaScript

In JavaScript, there is an easy way out from an infinite loop. We can use a break statement to exit from a loop immediately. A simple example of using break statement inside an infinite loop is as:

   var x = 1;
   while(true) {
     if(x == 3) break;

In this example, the while statement has set up as an infinite loop. The if statement checks that the value of x is equal to 3. If the value of x is 3, it exits the loop.

When JavaScript interpreter executes break statement, it skips the rest of code and continues the execution of script with the statement following loop. We can use the break statement in any type of loop, whether infinite or not.

Types of Loops (Iterations) in JavaScript

JavaScript language supports four types of loop statements for performing loop operations. They are:

  • for loops
  • for-in loops
  • while loops
  • do-while loops

The while loop is a loop statement that repeats a statement or a series of statements as long as the conditional expression tests to true.

A for loop is a loop statement that executes a statement or series of statements as long as the specified conditional expression evaluates to true.

The do while loop statement executes its statement blocks while its condition evaluates to true.

We will learn the functions, features and applications of each of these loops in the further tutorials one by one.

In this tutorial, you learned loops in JavaScript, and types of loop statement with various examples. Hope that you will have understood the basic concepts of loops, nested loops, and infinite loops in JavaScript.

In the next tutorial, we will learn for loop in JavaScript with example programs.
Thanks for reading!!!
Next ⇒ While Loop in JavaScript⇐ PrevNext ⇒