How to execute a for-loop in JavaScript
A for-loop is a control flow statement which is used to execute a block of code a number of times. The flow of the for-loop is specified after each execution of the code block (called an iteration).
Imagine a situation where you have to do a certain task a hundred times. How would you do that? You could type the command to achieve the task a hundred times, or maybe copy-paste it repeatedly.
Of course, that would be quite tedious. This is where loops come into use. When using a for-loop, those hundred lines of code can be written in as few as three to four statements.
Syntax
This is what a for-loop looks like in JavaScript:
/* for-loop syntax in JavaScript */for (variable_initialize; condition; change_variable) {// code block to be executed}
Arguments
-
variable_initialize(optional): This statement is executed once before the execution of thefor-loopcode block. This is used to define the counter variable etc. you might be using to control the flow. -
condition: This statement defines the condition on which the control flow (each iteration) of thefor-loopdepends. -
change_variable: This statement is executed after each iteration of thefor-loop. This can be used to update the initialized control variable.
Note:
variable_initializeis optional since you can use an already initialized variable instead. Do not forget the;following thevariable_initializeeven if you decide to skip it!
Flow Diagram
Examples
This code will print out the incremented temp variable from 0 through 4, with an updated value in each iteration, followed by the word : Educative!. The expanded version for the same code is also given in the second code tab, which should be helpful in understanding how exactly the for-loop executes.
for (var temp = 0; temp < 5; temp++) {// Runs 5 times, with values of temp 0 through 4.console.log(temp + ": Educative!");}
Free Resources