Welcome to the JavaScript tutorials, we already covered JavaScript if else, JavaScript switch case and JavaScript while loop. Today we will discuss the JavaScript for loops. If you have learnt any language, then must have heard about the for loop. The JavaScript for loops can be used to run the statements for a number of mentioned times.
JavaScript for loops – Syntax
Now, we will see the for loop syntax, and discuss it in detail. Let’s see the JavaScript for loop syntax first.
Look at the above picture, i think you don’t need any explanation. But still we will try to make it simple for those who are new to JavaScript for loops.
- Initial value – It will be used to initialize the value that will act as a counter.
- Test value – It is the deciding moment for the ’for loop’. Because it will decide whether to execute the loop or not. If the condition test will fail, then it will not execute any more.
- Increment – The initial value will be incremented after every execution.
- Statements – In the above example, the statements resemble the code that will be executed for the specified number of times.
JavaScript for loops – Example
Now we will see the ease of using for loop. We have just used ‘sharp’ variable that will hold the initial value. Now if the value of sharp is less than 6, then for loop will increment and execute the code. It will repeat the process, until the sharp value will not become 6.
<html > <head> </head> <body> <script type="text/javascript"> for (sharp=1; sharp<6; sharp++) { document.write("<b>The SharpLesson says 'Hi' " + sharp + " times" +"</b>") document.write("<br>") } </script> <p>What happened?: <p>The initial value set <b>sharp</b> equal to 1. <p>As long as <b>sharp</b> is less than 6, the loop will continue to run. <p><b>sharp</b> will increase by 1 each time the loop runs. </body> </html>
The output will be:
The SharpLesson says 'Hi' 1 times The SharpLesson says 'Hi' 2 times The SharpLesson says 'Hi' 3 times The SharpLesson says 'Hi' 4 times The SharpLesson says 'Hi' 5 times What happened?: The initial value set sharp equal to 1. As long as sharp is less than 6, the loop will continue to run. sharp will increase by 1 each time the loop runs.
We have already explained the example in its result. It means we need not to write any further explanation of the above shown example.
Conclusion
We have just covered the JavaScript for loops. We saw for loop syntax, and the example to show the working of for loop to a fresher. Because, they require a proper explanation to understand the basics. We at sharplesson believe that practice is the key to success. Never forget to practice what you have learnt, else it is a human nature. We tend to forget things easily.