freecoding.school100% FREE · NO SIGNUP
Script SpringsISSUE #27 of 29

for...of · iterating values

SparkyVSNaN the Trickster
Sparky saysfor...of iterates the values of any iterable — arrays, strings, Maps, Sets.

for (const item of arr) gives you values directly (no index bookkeeping). It works on anything iterable: arrays, strings, Map, Set, and generators. Need the index too? Use arr.entries() or .forEach. This is usually the loop you want for collections.

Power-ups you unlock

NaN the Trickster attacks — common mistakes

Boss battleSum an array with for...of, then loop a string’s characters.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>let sum=0; for(const n of [1,2,3,4]) sum+=n;
let chars=[]; for(const c of 'hi') chars.push(c);
document.getElementById('o').textContent='sum='+sum+' chars='+chars.join(',');</script></body></html>
▶ Open the interactive comic issue
‹ For...In · Iterating KeysWhile · Do-While ›