Skip to content
Loops: for and while
step 1/7

Reading — step 1 of 7

Learn

~2 min readControl Flow

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

js

Three parts in the parens, separated by semicolons:

  1. Initialization (let i = 1) — runs once at the start.
  2. Condition (i <= 5) — checked before each iteration.
  3. Update (i++) — runs after each iteration.

Use let, not var, in the initializer for proper block scoping.

while — repeat until condition is false

js

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

js

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

js

Works on arrays, strings, Sets, Maps, generators. This is the modern way to iterate an array's values.

Need the index too? Use entries():

js

for...in — iterate KEYS of an object (not for arrays)

js

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

js

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…