JavaScript Tutorial: Loops
for, while, for...of, for...in, forEach — loop over everything JavaScript throws at you.
Repetition without repetition
Writing the same code 100 times is why loops were invented. JavaScript has five different loop constructs — each with its ideal use case.
The rule of thumb: `for...of` for arrays and iterables, `for...in` for object keys, `forEach` for simple array iteration, classic `for` when you need index control.
What you'll learn in this JavaScript loops tutorial
This interactive JavaScript tutorial has 10 hands-on exercises. Estimated time: 20 minutes.
- for — the classic — The classic `for` loop gives you full control: start, condition, increment.
- for...of — loop over any iterable — `for...of` is the modern way to loop over arrays, strings, Maps, Sets — anything iterable.
- entries() — index AND value — Need both the index and the value while iterating? `.entries()` gives you both as `[index, value]` pairs.
- for...in — loop over object keys — `for...in` iterates over the **keys** of an object:
- while — loop until something changes — `while` keeps going as long as the condition is true. Use it when you don't know upfront how many iterations you need.
- break — exit early — `break` immediately exits the loop — even if there are items remaining.
- continue — skip this one — `continue` skips the rest of the current iteration and jumps to the next one.
- forEach — simplest array loop — Arrays have a `.forEach()` method — a cleaner version of a for loop for simple iteration:
- Nested loops — with care — Loops inside loops. The inner loop runs completely for every outer iteration.
- FizzBuzz — the classic interview question — Almost every programming interview has this. You now have everything you need.
JavaScript Loops concepts covered
- Repetition without repetition