• USA : +1 973 910 5725
  • INDIA: +91 905 291 3388
  • info@tekslate.com
  • Login

Loops in JavaScript

JavaScript while Loops

While writing a program, there may be a situation when you need to perform some action over and over again, In such situation you would need to write loop statements to reduce the number of lines.

JavaScript supports all the necessary loops to help you on all steps of programming.

While Loop

The most basic loop in JavaScript is the while loop which would be discussed in this tutorial. 

Syntax 

While (expression)

statement(s) to be executed if expression is true

}

The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is true. Once expression becomes false, the loop will be exited.

Example

Following example illustrates a basic while loop

<script type=”text/javascript”>

<!—

var count=0;

document.write(“starting Loop” +  “<br /”);
while (count<10)

{

document.write(“Loop stopped”);

// — >

</script> 

 

do… While Loop

The do…while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.

Syntax 

do {

Statement(s) to be executed;

} while (expression);

Note the semicolon used at the end of the do…while loop

Example

Let us write above example in terms of do… while loop.

<script type=”text/javascript”>

<!—

var count=0;

document.write(“starting Loop”  +   “<br/>”);

count++;

}

while(count<0);

document.write(“Loop stopped:”);

// – – >

</script>

 

JavaScript for Loops

We have seen different variants of while loop. This chapter will explain another popular loop called for loop.

For Loop

The for loop is the most compact form of looping and includes the following three important parts :

The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.

The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.

The iteration statement where you can increase or decrease your computer.

You can put all the three parts in a single line separated by a semicolon.

Syntax 

for(initialization; test condition; iteration statement)

{

statement(s) to be executed if test condition is true

}

 

Example

Following example illustrates a basic for loop:

<script type=”text/javasscript”>

<!—

var count;

document.write(“starting Loop” + “<br />”);

for(count=0; count<10;count++)

{

document.write(“Current count :” +  count);

document.write(“<br/>”);

}

document.write(“Loop stopped”);

//- – >

</script>

 

JavaScript for… in loop

There is one more loop supported by javascript. It is called for..in loop. This loop is used to loop through an object properties.

Because we have not discussed objects yet, So you may not feel comfortable with this loop. But once you will have understanding on JavaScript objects then you will find this loop very useful.

Syntax

for(variablename in object)

{

statement or block to execute

}

In each iteration one property from connect is assigned to variable name and this loop continues till all the properties of the object are exhausted.

Example

Here is the following example that pri out the properties of web browser’s Navigator object:

<script type=”text/javascript”>

<!—

varapropery;

document.write(“Navigation object propertoies<br/>”);

for(aproperty in navigator)

{

document.write(aproperty);

document.write(“<br/>”);

}

document.write(“Exiting from for loop!”);

//- – >

</script>

JavaScript Loop Control

JavaScript provides you full control handle your loops and switch statement. There may be a situation when you need to come out of a loop without reaching its bottom. There may also be a situation when you want to skip a part of your code block and want to start next iteration of any loop respectively.

The break statement

The break statement, which was introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces.

Example 

The example illustrates the use of break statement with a while loop. Notice how the loop breaks out early once X reaches 5 and reaches document. while(..) statement just below to closing curly brace.

<script type=”text/javascript”>

<!—

var x=1;

document.write(“Enterning the loop<br/>”);

while(x<20)

{

if (x==5)

{

break;   // breaks out a loop completely

}

x=x+1;

document.write(x+ “<br/>);

document.write(“Existing the loop!<br/>”);

// – – >

</script>.

 

The Continue statement

The continue statement tells the interpreter to immediately start the next iteration of the loop and skip remaining code block.

When a continue statement is encountered, program flow will move to the loop check expression immediately and if condition remain true then it start next iteration otherwise control comes out of the loop.

Example 

This example illustrates the use of a continue statement with a while loop. Notice how the continue statement is used to skip printing when the index held in variable x reaches 5:

<script type=”text/javascript”>

<!—

var x=1;

document.write(“Entering the loop<br/>”);

while(x<10)

{

x=x+1;

if(x==5)

{

continue;   // skill rest of the loop body

}

document.write(x+”<br/>”);

}

document.write(“Existing the loop!<br/>”);

//- – >

</script>

 

Using labels to control the flow 

Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more precisely.

A label is simply an identifier followed by a colon that is applied to a statement or block of code. We will see two different examples to understand label with break and continue.

 

Note 

Line breaks are not allowed between the continue or break statement and its label name. Also, there should not be any other statement in between a label name and associated loop.

 

Example 1

<script type=”text/javascript”>

<!—

document.write(“Entering the loop!<br/>”);

outerloop: //This is the label name

For (vari=0; i<5;i++)

{

document.write(“outerloop:” + i+ “<br/>”);

innerloop:

for(var j=0;j<5;J++)

{

if(j>3)   break;                        // Quit the innermost loop

if(i==2) break innerloop;       // Do the same thing

if(i==4) break outerloop;       // Quit the outer loop

document.wirte(“Exiting the loop!<br/>”);

// – ->

</script>

 

Example 2

<script type=”text/javascript”>

<!—

document.write(“Entering the loop! <br/>”);

outerloop:                    // This is the label name

for(vari=0;i<3;i++)

{

if(j==3)

continueouterloop;

}

document.write(“innerloop : ” + j + “<br/>”);

}

}

document.write(“Existing the loop!<br/>”);

//

</script>

Summary
Review Date
Reviewed Item
Loops in JavaScript
Author Rating
5

“At TekSlate, we are trying to create high quality tutorials and articles, if you think any information is incorrect or want to add anything to the article, please feel free to get in touch with us at info@tekslate.com, we will update the article in 24 hours.”

0 Responses on Loops in JavaScript"

    Leave a Message

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

    Site Disclaimer, Copyright © 2016 - All Rights Reserved.

    Support


    Please leave a message and we'll get back to you soon.

    I agree to be contacted via e-mail.