A JavaScript for
loop allows you to execute code a specific number of times by using a for
statement that combines three statements in a single block of execution. Here’s the syntax:
for (assignment; condition; update;){
code to be executed;
}
The for
statement uses the three statements as follows when executing the loop:
assignment: This is executed before the loop begins and not again. It is used to initialize variables that will be used in the loop as conditionals.
condition: This expression is evaluated before each iteration of the loop. If the expression evaluates to true
, the loop is executed; otherwise, the for
loop execution ends.
update: This is executed on each iteration, after the code in the loop has executed. This is typically used to increment a counter that is used in condition.
The following example illustrates a for
loop and the nesting of one loop inside another:
for (var x=1; x<=3; x++){
for (var y=1; y<=3; y++){
console.log(x + " X " + y + " = " + (x*y));
}
}
The resulting output to the web console is:
1 X 1 = 1
1 X 2 = 2
1 X 3 = 3
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9