Skip to main content

Looping in JavaScript

Loops let you repeat actions and iterate over data. JavaScript has several loop types, but you’ll use two of them most of the time: for...of and the classic for loop.

for…of — iterate over arrays

The cleanest way to loop through an array:
JavaScript’s for...of is Python’s for...in. Same concept, different keyword. Use const for the loop variable if you don’t need to reassign it inside the loop.

When you need the index

.entries() is JavaScript’s equivalent of Python’s enumerate().

for…in — iterate over object keys

for...in is for objects. for...of is for arrays. Mixing them up is a common mistake. for...in on an array gives you index strings (“0”, “1”, “2”), not the values.
For objects, you can also use Object.entries() which is often cleaner:

Classic for loop

The traditional loop with a counter variable. Use it when you need precise control over the iteration:
Three parts: for (initialization; condition; update)
  • initialization: let i = 0 — runs once before the loop
  • condition: i < 5 — checked before each iteration
  • update: i++ — runs after each iteration

Practical example

Looping backwards

while and do…while

For loops where you don’t know the count in advance:
while loops are uncommon in web development. You’ll mostly use for...of for arrays and array methods like .map() and .forEach(). But while is useful for retry logic and polling patterns.

break and continue

Control the flow inside loops:

Loops vs array methods

In modern JavaScript, you’ll often choose between a loop and an array method. Here’s when to use each:
Prefer array methods when possible — they’re more readable and less error-prone. Use for...of when you need break, continue, or complex multi-step logic inside the loop.

What’s next?

You’ve covered working with data — arrays, objects, destructuring, spread, JSON, conditionals, and loops. This is the toolbox you’ll use in every web application. Next up: asynchronous JavaScript. This is where things get interesting — you’ll learn how JavaScript handles operations that take time, like fetching data from your FastAPI backend.

Why async matters

Understand why JavaScript handles time differently