The for loop iterates through 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.
Syntax
for (initialization ; condition ; updatevalue) { // code block to be executed }
The initialization expression initializes and executes only once. You typically use the initialization expression to initialize a counter variable.
The condition is then evaluated.
If the condition is false, the for loop is terminated.
if the condition is true, the block of code inside of the for loop is executed.
The updatevalue updates the value of initialization when the condition is true. Normally you would use the updatevalue to update the counter variable.
The condition is evaluated again. This process continues until the condition is false.
Examples
for (var counter = 1; counter <= 5; counter++) { console.log('Inside the loop:' + counter); } console.log('Outside the loop:' + counter);
And you should see this in the console
Inside the loop:1 VM43:2 Inside the loop:2 VM43:2 Inside the loop:3 VM43:2 Inside the loop:4 VM43:2 Inside the loop:5 VM43:4 Outside the loop:6
First of all we declare a variable named counter and initialize it to 1.
Second, display the value of counter in the Console window if counter is less than or equal to 5.
Third, increase the value of counter by one in each iteration of the loop.
No initialization
defined
The following example uses a for loop that omits the initialization part
var counter = 1; for (; counter <= 5; counter ++) { console.log('Inside the loop:' + counter); }
Run this and again you will see the following in the console
Inside the loop:1 Inside the loop:2 Inside the loop:3 Inside the loop:4 Inside the loop:5
No condition defined
Similar to the initialization expression, the condition expression is optional. If you omit the condition expression, you need to use a break statement to terminate the loop.
Lets see an example
for (let counter = 1;; counter++) { console.log('Inside the loop:' + counter); if (counter > 5) { break; } console.log('After the loop:' + counter); }
Note there is noticeable difference between outputting to the console before and after the break. Look at this output
Inside the loop:1 After the loop:1 Inside the loop:2 After the loop:2 Inside the loop:3 After the loop:3 Inside the loop:4 After the loop:4 Inside the loop:5 After the loop:5 Inside the loop:6
Infinite loop
If the test condition in a for loop is always true, it runs forever. For example,
// infinite loop for(let i = 1; i > 0; i++) { // block of code }
This is another common bug in programs, unless for some reason you want an infinite loop