Syntax
for (initializer; stopping condition; iterator) { code block; }
- the for loop statement is comprised of three expressions - initializer, stopping condition, and iteration statement
- initializer 'initializes' the for loop and can declare the iterator variable
- stopping condition is the conditional statement that defines the condition under which the for loop will keep going - as long as this stopping condition is
true
, the code block inside{}
of the for loop will continue to run. When this stopping condition evaluates tofalse
, the loop stops.- iteration statement updates the iterator variable on each loop
> ex)
for (let i = 0; i < 5; i++) { console.log(i); } /* Prints: 0 1 2 3 4 */
Syntax
let variableName; while (stopping condition) { code block; iteration statment; }
for loop
if you know how many times you would run the loop, and use while loop
if you don't know in advance how many times a loop should runIf you need to have a block of code run at least once regardless of any conditions, but after running once, you want it to run only when some conditions are met, you can use the do..while statement
instead of the while loop
Syntax
let variableName; do { code block; iteration statement; } while (stopping condition);
If you want a loop to stop before the pre-set stopping condition renders false
if another special condition is met, you can do so using the break
keyword
Syntax
for (initializer; stopping keyword; iteration statement) { if (break condition) { break; } code block; }
or
for (initializer; stopping keyword; iteration statement) { code block; if (break condition) { break; } }