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.
const fruits = ["Apple", "Banana", "Cherry"];for (const fruit of fruits) { console.log(fruit);}// Apple// Banana// Cherry
JavaScript
Python
Copy
for (const item of items) { console.log(item);}
Copy
for item in items: print(item)
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.
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:
Copy
const user = { name: "Sarah", age: 28, role: "admin" };for (const [key, value] of Object.entries(user)) { console.log(`${key}: ${value}`);}
For loops where you don’t know the count in advance:
Copy
// while — checks condition firstlet attempts = 0;while (attempts < 3) { console.log(`Attempt ${attempts + 1}`); attempts++;}// do...while — runs at least once, checks condition afterlet input;do { input = getInput(); // Runs at least once} while (!isValid(input));
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.
In modern JavaScript, you’ll often choose between a loop and an array method. Here’s when to use each:
Task
Use
Transform each item
.map()
Keep some items
.filter()
Find one item
.find()
Check if something exists
.includes() or .some()
Calculate a total
.reduce()
Side effects (log, DOM update)
.forEach() or for...of
Need break/continue
for...of or for
Need the index
.forEach() or for...of with .entries()
Copy
// Array method approach — usually preferredconst activeUsers = users.filter(u => u.active).map(u => u.name);// Loop approach — needed for complex logic or early exitconst results = [];for (const user of users) { if (user.role === "banned") continue; if (results.length >= 10) break; if (user.active) { results.push(user.name); }}
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.
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.