The for loop in JavaScript is kind of, like the while loop. But the for loop is way more powerful than the while loop.
The for loop has inbuilt features, by which you can reduce lines of code.
So far we have seen, how while loop was used to document.write "Hello World" 5 times.
var x = 1 while (x <= 5) { document.write("Hello World") x = x + 1 }
The same program could be reduced to two lines of code using the for loop.
Let us see below.
Let us dive into the code directly and understand it eventually.
<html> <body> <script language = "javascript" type = "text/javascript"> for (var x = 1; x <= 5; x++) { document.write("Hello World! ") } </script> </body> </html>
And yes ! As said, we have reduced the code to two lines and that's all.
And the entire magic happens in the for loop
Now, if we break the contents of for loop, we get :
var x = 1
x <= 5
x++ ('x++' is same as 'x = x + 1')
All together forms the for loop.
for (var x = 1; x <= 5; x++) { document.write("Hello World! ") }
Let us look at another example to print the numbers, 0 to 5 using for loop. And understand for loop in detail.
<html> <body> <script language = "javascript" type = "text/javascript"> for (var x = 0; x < 6; x++) { document.write(x, ", ") } </script> </body> </html>
Even in this case, there are two lines code.
In the initialisation section(i.e. var x = 0), the initial value of x is initialised with 0.
So in the 1st iteration,
The control comes the for loop and since in the conditional part we have x < 6, it checks, if the value of x is less than 6(i.e. x < 6).
In this case the value of x is 0. Which is less than 6.
So, the control enters the for loop.
for (var x = 0; x < 6; x++)
and finds the document.write statement,
document.write(x, ", ")
So, it prints the current value of x(i.e. 0)
Next, in the increment section x++, it increments the value of x by 1. And the value of x becomes 1.
And the second Iteration starts.
Same way, the control comes the for loop and checks, if the value of x is less than 6(i.e. x < 6).
In this case the value of x is 1. Which is less than 6.
So, the control enters the for loop.
for (var x = 0; x < 6; x++)
And finds the document.write statement,
document.write(x, ", ")
So, it prints the current value of x(i.e. 1)
Similarly, in the increment section x++, it increments the value of x by 1. And the value of x becomes 2.
Similarly, the third, fourth and fifth Iteration continues incrementing the value of x, printing it.
Now, in the 7th Iteration, the control comes to the for loop and checks, if the value of x is less than 6(i.e. x < 6).
And in this case the value of x is 6. Which is equal to 6.
So, the condition fails and the loop exits.
So, the one liner for loop does a lot for us.
for (var x = 0; x < 6; x++)
It initialises the value of x with 0 initially (i.e. var x = 0). Then increments the value of x with 1(i.e. x++). Also handles the conditional part (i.e. Continue the loop until x < 6).