JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It makes the code compact. It is mostly used in array.
There are four types of loops in JavaScript.
- for loop
- while loop
- do-while loop
- for-in loop
JavaScript For loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number of iteration is known. The syntax of for loop is given below.
Let’s see the simple example of for loop
The While Loop
Loops can execute a block of code as long as a specified condition is true. The while
loop loops through a block of code as long as a specified condition is true.
Example
In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10:
The Do While Loop
The do while
loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
Example
The example below uses a do while
loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested: