Loops offer a quick and easy way to do something repeatedly. This chapter of the JavaScript Guide introduces the different iteration statements available to JavaScript.
You can think of a loop as a computerized version of the game where you tell someone to take X steps in one direction, then Y steps in another. For example, the idea “Go five steps to the east” could be expressed this way as a loop:
for (let step = 0; step < 5; step++) { // Runs 5 times, with values of step 0 through 4. console.log(‘Walking east one step’); }
for statement:
for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop.
A for statement looks as follows:
for ([initialExpression]; [conditionExpression]; [incrementExpression]) statement
When a for loop executes, the following occurs:
while statement:
A while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows:
while (condition) statement
The condition test occurs before statement in the loop is executed. If the condition returns true, statement is executed and the condition is tested again. If the condition returns false, execution stops, and control is passed to the statement following while.
To execute multiple statements, use a block statement ({ … }) to group those statements.