Open original
Info
Demo 3.7

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.

Next demoThe Document Object Model (DOM)
Keyboard Shortcuts
⌘ Z / ⌘ ⇧ ZCtrl Z / Ctrl ⇧ Z Undo / redo
Tab / ⇧ TabTab / ⇧ Tab Indent / unindent selection
⌘ ] / ⌘ [Ctrl ] / Ctrl [ Indent / unindent lines
⌘ ACtrl A Select all
⌘ DCtrl D Select next occurrence of selection
⌘ /Ctrl / Comment / uncomment lines
Ctrl SpaceCtrl Space Autocomplete
Ctrl EnterCtrl Enter Reset layout
⌘ ⌥ [ / ⌘ ⌥ ]Ctrl ⇧ [ / Ctrl ⇧ ] Fold / unfold block
Code
The editor didn't load — try refreshing the page. Navigation, shortcuts and the info panel still work in the meantime.
Preview
Dimensions0 × 0
Delay
Console