Loop in JavaScript With Example – Learn How to Construct Loops

Many times we need to write the same block of codes to run over and over again in a row. Instead of adding several almost equal lines in a script, we use loops to perform a task. This article specially designs for loops in JavaScript. Here, you will learn the working of different types of JavaScript loops like: for loop, while loop, do-while loop, for/in loop, and infinite loop with their syntax and examples.

We will cover the break statement and continue statement at the end of this JavaScript loops tutorial.

Different types of loops in JavaScript

What are Loops in JavaScript?

Loops in JavaScript are used to execute the same block of code a specified number of times until the specified condition is true. 

There are mainly two types of loops in JavaScript:

  • Entry Controlled Loops – The condition statement will check before entering the loop. The entry controlled loops are For and while loop.
  • Exit Controlled Loops – A test condition is evaluated at the end of the body. The loop body will execute at least once, whether the test condition is true or false. do while loop is exit controlled loop.

1. for Loop in JavaScript

for loop in JavaScript iterate through a block of code a number of times. It consists of three parts, which separate by semicolons. The first is the initializer which initializes the loop and executes only once at the start. The second is test condition, where a conditional expression evaluates to true, the body of the loop is executed. When false, the loop terminates. The third part is an update which is invoked after each iteration. The updates typically increment or decrement the loop counter.

In a for loop, all the three parts i.e initializer, test condition, and updates are written together in a single line (called an iteration statement), whereas in a while they are scattered and lie at different places. This makes a for loop more readable than a while loop and as the result more easily maintainable.

  • Initialization Condition: Here, we initialize the variable in use. It marks the start of a for loop.
  • Testing Condition: It must return a boolean value. It is called 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 true, the statement in the loop body is executed.
  • Increment/decrement: It is used for updating the variable for the next iteration.
  • Loop Termination: The loop will get terminate making the end of its life cycle.

Do you know What is JavaScript Variable and How to declare them?

2. for/in Loop in JavaScript

for/in loop iterate through the properties of an object in JavaScript. With each iteration, JavaScript assigns the name of the property to the variable items.

For – in loops also return properties and method that are inherited through the prototype chain. An easy way to skip properties and functions that are not part of the object itself using the built-in OwnProperty method.

JavaScript For...in Loop

The Syntax of JavaScript For Loop

for (variableName in Object)
{
Statement(s);
}

In each iteration, one of the properties of an object is assigned to the variable named VariableName and this for loop continues until all the properties of the object are processed.

Example of JavaScript For Loop

<script type = “text/javascript”>
var languages = { first : “c”, second: “Java”, third: “Python”, fourth: “PHP”, fifth: “JavaScript”};
// iterate through every property of the object language // and print all of them using for.. in loops
for( itr in languages)
{ 
Document.write(languages[itr2] + “<br>”);
}
</script>

Output:

C

Java

Python

PHP

JavaScript

3. While loop in JavaScript

While loop in JavaScript iterates through a block of code until the specified condition is true. It is the same as looping. JavaScript offers several options to repeatedly run a block of code, do –while.

The condition is first evaluated. If true, then while the statement will be executed. This is repeated until the condition becomes false. This is known as a pre-test loop because the condition is evaluated before the block is executed. The number ++ statement is called the updater. Removing it will result in an infinite loop. You must always include the base condition that guarantees the termination of the loop in JavaScript.

Also, read – 8 Important Features of JavaScript 

JavaScript While Loop

The syntax of JavaScript While Loop

While (condition) {
// code block to be executed
}

Example of JavaScript While Loop

In the following example, the code in the loop will run over and over again, as long as a variable(x) is less than 10.

while(i<10) {
  text+= “The number is “ +1;
  i++;
}

Output

text= The number is 2

text = The number is 3

text = The number is 4

text = The number is 5

text = The number is 6

text = The number is 7

text = The number is 8

text= The number is 9

Explore the 10 Applications of JavaScript into Real World

4. do-while Loop in JavaScript

do-while loop in JavaScript through a block of code until the specified condition is true. The block is executed first and then the condition is evaluated.

The do/while loop is an extension of the while loop. Do While loop executes the code block, before checking if the condition is true, and it will repeat the loop as long as the condition is true.

JavaScript Do-while Loops

The syntax of JavaScript Do-while Loop

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

Example of JavaScript Do-while Loop

The example below uses a do/ while loop in JavaScript. This loop will gets executed atleast once even if the condition is false.

do {
  text + = “ The number is “ +1;
  i++ ;
}
While (i<10);

Output

text = The number is 2

text = The number is 3

text = The number is 4

text = The number is 5

text = The number is 6

text = The number is 7

text = The number is 8

text = The number is 9

text = The number is 10

5. Infinite Loop in JavaScript

One of the most common mistakes while implementing any sort of looping is that it may not exist ever, that is the loop runs for infinite time. This happens when the condition fails for some reasons.

Example of JavaScript Infinite Loop

<script type = “text/javascript”>
//JavaScript program to illustrate infinite loop 
//Infinite loop because condition is not opt
//condition should have been i>0

for(var i =5; i!=0; i==2)
{
   document.write(i);
}
var x =5;
//infinite loop because update statement 
//is not provided
While(x == 5) 
 {
  document.write( “In the loop”);

</script>
</body>
</html>

Output

In the loop
In the loop
.
.
N times.

Explore the Advantages and Disadvantages of JavaScript

Comparing for and While loop in JavaScript

An example of for loop in JavaScript together with the car names from the cars array.

Example

var cars = {“BMW”, “VOLVO”, “SAAB”, “FORD”};
var i=0;
var text = “ “;
for ( i cars[i]); {
  text + = cars[i]+ “<br>”;
i++;

Output

BMW

VOLVO

SAAB

FORD

While loop to get the car names from the car array

Example

var cars = [“BMW”, “VOLVO”, “SAAB”, “FORD”];
  var i = 0;
  var text = “ “;
 while(cars [i]) {
  text + =cars[i] + “<br>”;
 i++;

Output:

BMW

VOLVO

SAAB

FORD

JavaScript Break Statement

When JavaScript encounters the break statement in a loop it immediately exits the loop without executing any other statements in the loop control is immediately transferred to the statements following the loop body.

Example

var sum =0;
for( var i =1; i<= 10000;i++)
{
  sum + = 1;
 if(i ==50)
  break; //Immediately transfers control outside the for block.
}
}
alert( “ Sum = “ +sum); 
}

Output

sum = 1275

JavaScript Continue Statement

When JavaScript encounters a continue statement in a loop it stops the execution of the current iteration and goes back to the beginning of the loop to begin the next section.

Example

for ( var i =1; i<=0; i++)
 {
   if ((i%2)!= 0)
    {
      Continue;
    }
   alert(i);
 }

Output

2, 4,6, 8, 10

Example

var number = 0;
while( number <= 20) {
   number ++;
if ( number % 2) ! =0)
{
continue;
}
alert( number);
}

Output

2, 4, 6, 8,10, 12, 14, 16, 18 , 20

When the continue statement is executed the control is returned directly to the while test condition and the number ++ expression is not evaluated, thus causing an infinite loop in JavaScript.

Very often, we write code, and we want the same block of code to run over and over again a row. We use loops to perform a task.

Summary

So, this was all about different types of loops in JavaScript: for loop, for..in loop, do while loop, while loop, an infinite loop with examples. Along with this, we discussed the break and continue statements in JavaScript. You may also like our next tutorial of Loop Control in JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.