Loops
JavaScript supports the standard loop constructs you have seen in other programming languages:
let counter = 0; while (counter < 10) { console.log(counter); counter++; }
In a do
-while
loop, the loop's body is executed once, and then, if the condition holds, the program returns to the top of the block.
let counter = 10; do { console.log(counter); counter++; } while (counter < 10);
When it comes to counter-controlled loops (when we know exactly how many iterations we need, e.g. when we go over the elements of an array), the for
loop provides a more compact syntax:
for (let counter = 0; counter < 10; counter++) { console.log(counter); }
You can cram in multiple variables, update expressions:
const arr = [10, 20, 30, 40, 50]; for (let i = 0, j = arr.length - 1; i < j; i++, j--) { const temp = arr[i] arr[i] = arr[j] arr[j] = temp } console.log(arr);
The while
and do
-while
loops are best for event-controlled loops (when the number of iterations is unknown before runtime, e.g., when we read data from a file and don't know how many lines or how many values are there).
break
& continue
The break
statement exits out of a loop, while the continue
statement will skip to the next iteration:
const arr = [10, 20, 30, 40, 50]; const target = 40; let index = -1; for (let i = 0; i < arr.length; i++) { if (arr[i] === target) { index = i; break; // stop early! } } console.log(index);
const arr = [10, , 30, , 50]; let count = 0; let sum = 0; for (let i = 0; i < arr.length; i++) { if (arr[i] === undefined) { continue; // ignore missing data! } count++ sum += arr[i] } const avg = count === 0 ? 0 : sum / count; console.log(avg);