JavaScript Loops
For Loop
The for loop is used to execute a block of code a certain number of times.
- expression1 is executed (one time) before the execution of the code block.
- expression2 is executed before each iteration of the code block.
- expression3 is executed after each iteration of the code block.
Additional Notes
- Technically, all 3 expressions in the for loop are optional. However, if you omit expression2, you must include a break statement inside the code block to avoid creating an infinite loop.
- JavaScript does not have a foreach loop. However, it does have a function forEach that can be used to iterate over arrays. The forEach function takes a callback function as an argument, which is executed for each element in the array.
While Loop