Summary

For loops

js
for(let i = 0; i <= 5; i = i + 1) {
	// body
}

While loops

js
while(bool) {
	// body
}

Concept

For loops

  • For repeating a task x number of times
  • Initialise an incrementer, check if condition is true, run the loop body, increment, check if the condition is still true, repeat

While loops

  • For repeating a task until a condition is met
  • Check if condition is true, run the loop body, check if condition is still true, repeat

Beware infinite loops

Application

Loops in math

js
let sum = 0;
for(i = 0; i <= 4; i = i + 1) {
	sum = sum + i; // summation
}
sum; // -> 10
js
let prod = 1;
for(i = 1; i <= 4; i = i + 1) {
	prod = prod * i;
}
prod; // -> 24