JavaScript Loops
Very often you may want the same block of code to run over and over again. To perform such tasks most of the programming language has loop constructs. Loops in JavaScript execute the same block of code a specified number of times or while a specified condition is true. In JavaScript there are two different kinds of loops:
1. For Loop: For loop is used to loops through a block of code for a specified number of times. The for loop is used when you know in advance how many times the script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment) { // code to be executed } E.g. The example below defines a loop that starts with i=1. It will continue until i is less than, or equal to 5. i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any comparing statement. Output: Number:1 Number:2 Number:3 Number:4 Number:5 2. While Loop: While loop is used when you want the loop to execute and continue executing while the specified condition is true. Syntax: while (var<=endvalue) { // Enter here the code to be executed } Note: The <= could be any comparing statement. E.g Using a for loop to display 5 numbers
Result
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
3. The do...while Loop
The do...while loop is just a variant of the while loop. In such loop the block of code is always executed atleast once. The loop will repeat as long as the specified condition is true.
Syntax:
do
{
// Enter here the code to be executed
}
while (var<=endvalue); E.g. Using do…while loop to display numbers
Output: Number:0 Number:1 Number:2 Number:3 Number:4 Note: This loop will always be executed at least once, even if the condition is false, because the code is executed before the condition is tested. 4. JavaScript Break and Continue JavaScript has two special statements that can be used inside loops: a. break: The break command will break the loop and continue executing the code that follows after the loop (if any). E.g Using break statement to come out of the for loop
Output:
The number is 0
The number is 1
b. Continue: The continue command is used in case you need to break the current loop and continue with the next one.
E.g.
Output:
Number:0
Number:1
Number:3
Number:4
Number:5
Comments