Loops
Files in this demo
├─ index.html └─ script.js
A loop repeats code once per item, or until something stops being true.
for...of ~ start here
for (const cat of cats) {
console.log(cat);
}
Readable, hard to get wrong, and it’s what you want the vast majority of the time.
The classic for loop
for (let i = 0; i < cats.length; i++) {
console.log(i, cats[i]);
}
Three parts, separated by semicolons: where to start, how long to keep going, what to do each time round.
Use it when you need the position as well as the item. Note i < length, not i <= length ~ arrays count from zero, so the last position is one less than the length. Getting this wrong is so common it has a name: an off-by-one error.
forEach, map and filter
cats.forEach((cat) => console.log(cat));
const shouted = cats.map((cat) => cat.toUpperCase());
const short = cats.filter((cat) => cat.length < 8);
forEach does something with each item. map builds a new list by transforming each one. filter builds a new list of the ones that pass a test.
Once these click you’ll write far fewer for loops.
while
while (countdown > 0) {
countdown = countdown - 1;
}
Repeats until the condition goes false. If nothing inside ever changes the condition, it runs forever and freezes the page ~ though in this editor the loop guard will stop it and tell you.
Click to resume
Use the console below.