For Loop in JavaScript Example
Learn How to use for loop in javascript with example step by step
What is for loop
It is an entry control loop. The browser executes the statements inside the for loop, until the given conditional expression evaluates to false.
Syntax:
for ( initialization ; conditional expression; increment/decrement)
{
statement;
}
Example
for(var i=1; i<5; i++)
{
document.write(i);
}
Note: when you know exactly how many # of times the loop is going to get executed, use for loop.
Here, we initialize an “i” variable to 1 and set the condition, if i variable is less than 5 then increment the variable “i”.
Then inside the curly braces and we printed the variable “i”.
When the browser increments the value from 4 to 5, the given condition is false. So, browsers 1, 2, 3, and 4 will only print.
Conclusion
We can use a looping statement when there is a looping work situation. for loop, while loop, and do while loop all do the same thing but with a slight difference
I hope you find this guide useful and keep learning to code!