SQL PHP HTML ASP JavaScript articles and free scripts to download
 

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.


Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked


Join Our Email List
Email:  
For Email Newsletters you can trust
Basic Loops