This article will show you how to use the simplest JavaScript loop – the for loop, and provide code examples.
JavaScript for Loops
JavaScript’s for loops are used to execute a block of code repeatedly until a condition is met. The initial variables, condition that must be met, and the expression which progresses the loop are all defined within the loop expression.
for loop Syntax
JavaScript for loops follow the following syntax:
for (INITIALIZATION; CONDITION; FINAL_EXPRESSION) { //Code to be executed in the loop }
Note that:
- INITIALIZATION sets the variable which is used to control the loop
- This will usually be setting a counter to an initial value
- CONDITION sets the condition that the variable defined during INITIALIZATION must meet for the loop to resume
- As soon as this condition is no longer TRUE, the loop will exit
- FINAL_EXPRESSION is a line of code that will be executed at the end of each loop
- Usually this will modify the variable set by the INITIALIZATION code to move it closer to fulfilling the CONDITION
- Note that the variables defined when declaring a for loop are scoped to the code block within it
- This means that the code inside the loop can modify any of the above variables declared to control the loop
JavaScript for Loop Examples
This first example for loop will simply print a list of numbers:
for (let i = 0; i < 10; i++) { console.log(i); }
Above, the variable i is initialized to 0. The condition is set so that the loop will run so long as i is less than 10. Finally, the expression that is run at the end of each iteration is set to increment i by 1.
The above will result in this console output:
0 1 2 3 4 5 6 7 8 9
Note that the loop exits after the loop condition is met, as the condition is checked at the end of each iteration, not the beginning. Every iteration completes in full.
This example will loop through the values in an array:
var myArray = ["dog", "fish", "cat"] for (let i = 0; i < myArray.length; i++) { console.log(myArray[i]); }
The above will output:
dog fish cat
As array indexes start at 0, and the for loop only runs so long as the value i is less than the length of the array, every item in the array is printed.
Other Loops in JavaScript
There are other loop structures in JavaScript. If you can’t accomplish your objective with a for loop, try: