JavaScript Loops
Loops are used to execute code repeatedly. JavaScript has three different types of loops:
- For loop
- While loop
- Do…while loop
JavaScript For Loop
The for loop is the most common type of loop in JavaScript. The syntax for a for loop is as follows:
for (initialization; condition; increment) {
// code to be executed repeatedly
}
The initialization statement is executed once before the loop starts. The condition statement is evaluated before each iteration of the loop. If the condition is true, the code inside the loop body is executed. If the condition is false, the loop terminates. The increment statement is executed after each iteration of the loop.
Here is an example of a for loop:
In this example, the initialization statement is var i = 0. This statement assigns the value 0 to the variable i. The condition statement is i < 5. This statement checks if the value of i is less than 5. If it is, the code inside the loop body is executed. The increment statement is i++. This statement increments the value of i by 1.
Task
Edit the code to print numbers from 0 to 9. Run the above code and experiment with the code to get used to it.