JS Loop For
JavaScript has five looping constructs. for…of is the modern default for arrays, but each has a niche.
The five loops
| Loop | Best for | Example |
|---|---|---|
for (init; cond; step) | Counting, when you need the index. | for (let i = 0; i < 10; i++) |
for…of | Iterating values of an array, string, Set, Map. | for (const v of arr) |
for…in | Iterating keys of an object. | for (const k in obj) |
while | Loop until a condition fails. Condition first. | while (queue.length) |
do…while | Run 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);
The modern keyword for iterating values.
Discussion
Loading…