iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Loop For

JavaScript has five looping constructs. for…of is the modern default for arrays, but each has a niche.

The five loops

LoopBest forExample
for (init; cond; step)Counting, when you need the index.for (let i = 0; i < 10; i++)
for…ofIterating values of an array, string, Set, Map.for (const v of arr)
for…inIterating keys of an object.for (const k in obj)
whileLoop until a condition fails. Condition first.while (queue.length)
do…whileRun at least once, then check.do { … } while (!done)

The same task four ways

JS
const fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < fruits.length; i++) console.log(fruits[i]);
for (const f of fruits)                  console.log(f);
for (const i in fruits)                  console.log(fruits[i]); // i is "0","1","2"
fruits.forEach(f =>                      console.log(f));

break and continue

JS
for (const n of nums) {
  if (n < 0) continue;     // skip negatives
  if (n > 100) break;      // stop at the first big number
  console.log(n);
}
Note: Avoid for…in on arrays. It iterates property names (including inherited ones), not numeric indexes in order. Use for…of instead.
Tip: When you're transforming a list, reach for map / filter / reduce instead of a manual loop. They read top-to-bottom as a pipeline.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Loop For!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Iterate the values of the fruits array.

for (const f fruits) console.log(f);

Test yourself

Q1. Which loop iterates values directly?
Q2. `for…in` on an array is…
Q3. Skip to the next iteration with…

Discussion

Loading…