JavaScript for loop & break statement inside the loop

Like any other language JavaScript for loop is one of the important built in functions to develop scripts. For loop in JavaScript is similar to for loop in C or PHP language. Other scripting languages have also similar For loops like ASP for Next loop, PHP for loop etc.

Different types of Loops are used to execute different part of the code in different logics and conditions. Some time loops are recursively use part of a code for a number of times with conditional checking. We will learn different types of loops and their uses in this section.

For loop in client side JavaScript has three parts in its declaration. The first part initialize a variable, the second part checks the condition and the third part gives the steps in which the variable will change value. Here is the syntax.
for( initialization; condition; step ; ){
Statement }
We can print number 1 to 10 by using for loop.
for (var x = 1; x <= 10; x++)
{ document.write (x+"<br>");
In the above code we have added one line break after each step of printing of number so the numbers will be displayed vertically. Now let us try to display numbers starting from 10 to 0
for (var x = 10; x >= 0; x--)
document.write (x+"<br>")
In the first example x value is increased by 1 starting from 1 and in second example x value is decreased by 1 starting from 10

Using break to come out of loop

We can come out of the loop by using break statement inside the loop. Let us use one if condition to break the loop once x value reaches 5 . Here is the code with break statement.
for (var x = 1; x <= 10; x++)
document.write (x+"<br>");
if(x >5){break;}
The above code will display number 1 to 6 vertically. You can see once the value of x reaches 6 the if condition returns true and breaks the for loop.

Using step value higher than 1

If we want to use incremental value higher than 1 , then we can use step value. Here is the sample code with step value ( incremental value ) of 5
for(j=0;j<100;j += 5){


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here .

    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2021 All rights reserved worldwide Privacy Policy Disclaimer