0
Challenge · 10Just Enough JavaScript

Loops: for, while, for..of

JavaScriptused in ~100% of apps

Every single problem in this course comes down to visiting things one at a time and doing something with each. That is a loop. There are three you need and they are all the same idea wearing different clothes.

Core idea. A loop repeats a block of code. Use for..of when you just want each item, a counting for when you need the position, and while when you do not know in advance how many times you will go round.
Playground, this isn't a screenshot
the same job, three ways
for..of, you only need each item
for (const n of nums) {
  total = total + n;
}
counting for, you need the position too
for (let i = 0; i < nums.length; i++) {
  total = total + nums[i];
}
while, you stop on a condition, not a count
let i = 0;
while (i < nums.length) {
  total = total + nums[i];
  i = i + 1;
}

All three add up the same numbers. Pick the one that says what you mean.

↑ play a little first, then dig in