JavaScript for loop & break statement inside the loopDifferent 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.
We can print number 1 to 10 by using for loop.
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
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 loopWe 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.
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 1If 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
Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
|
More on Loops and Variables |