loops
Concept
Used when repeasting an action
Beware of conditions that can result in an infinite loop
For loops
- 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
js
for(initialiser; condition; increment) {
// body
}
for(let i = 0; i <= 5; i = i + 1) {
// body
}
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
js
while(condition) {
// body
}
while(true) {
// body
}
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