Reading — step 1 of 7
Learn
Repetition is what makes computers powerful. JavaScript has FOUR main loop types — knowing when to reach for each is part of writing clean code.
The classic for loop
Three parts in the parens, separated by semicolons:
- Initialization (
let i = 1) — runs once at the start. - Condition (
i <= 5) — checked before each iteration. - Update (
i++) — runs after each iteration.
Use let, not var, in the initializer for proper block scoping.
while — repeat until condition is false
Use while when the iteration count isn't known up front. Something inside the body must eventually make the condition false — otherwise infinite loop.
do...while — runs at least once
Condition is checked AFTER the body, so the body always runs at least once. Useful for input validation loops.
for...of — iterate values of an iterable
Works on arrays, strings, Sets, Maps, generators. This is the modern way to iterate an array's values.
Need the index too? Use entries():
for...in — iterate KEYS of an object (not for arrays)
Don't use for...in on arrays! It iterates string keys, can include inherited properties, and has no guaranteed order for older engines. For arrays, always use for...of.
break and continue
Choosing the right loop
- for...of — iterating values of an array, string, Set, etc.
- for...in — iterating keys of an object.
- classic
for— when you need the index or step by something other than 1. while— when the END is dynamic, not a count.- Array methods (next chapter —
map,filter,forEach) — for transformations and filtering.
In modern JavaScript, you'll often reach for array methods OVER classic for-loops for transformations. Save for for index-driven work or genuine imperative loops.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…