Loading...
Loading...
Repeat actions efficiently. The for, while, and do...while loop types.
Programs make decisions and repeat work. Conditionals choose paths, loops repeat actions, and nested structures combine both. Mastering control flow turns a script that runs once into software that reacts to data and user input.
Learn Loops in JavaScript — covering Why Loops?, for Loop, while Loop, do...while with interactive visual examples and step-by-step explanations.
Control flow is how programs decide what to do next. If a user is logged in, show the dashboard; otherwise, redirect to login. If a cart total exceeds a threshold, apply a discount. These everyday behaviors all depend on conditionals and loops.
This module walks through if/else, switch, for and while loops, and how to combine them without losing readability. Visual step-throughs help you see exactly which branch runs and how loop counters change on each iteration.
Understanding loops is essential for every JavaScript developer. It shows up in frontend UI code, backend APIs, and framework internals — and getting it wrong leads to bugs that are hard to trace. This chapter builds intuition with visuals so the behavior sticks.
Avoid repetition. Let the computer do the work.
Without loops
console.log(1); console.log(2); console.log(3); console.log(4); console.log(5); // ... tedious!
With a loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Done! Works for 5
// or 5,000,000A loop repeats a block of code while a condition is true. When the condition becomes false, the loop stops.
When you know how many times to repeat.
for (initialization; condition; update) { // code to repeat } // Example: for (let i = 0; i < 5; i++) { console.log(i); } // Output: 0, 1, 2, 3, 4
1. Init
let i = 0
Runs once
2. Condition
i < 5
Checked each loop
3. Update
i++
After each loop
// Common for loop patterns: // Count down for (let i = 10; i > 0; i--) { console.log(i); // 10, 9, 8, ... 1 } // Step by 2 for (let i = 0; i < 10; i += 2) { console.log(i); // 0, 2, 4, 6, 8 } // Loop through array const fruits = ["apple", "banana", "cherry"]; for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); }
When you don't know how many iterations ahead of time.
while (condition) { // code repeats as long as condition is true } // Example: keep doubling until >= 100 let n = 1; while (n < 100) { n = n * 2; } console.log(n); // 128
while (n < 100) { n = n * 2; }
⚠️ Infinite loop danger! If the condition never becomes false, the loop runs forever and crashes the browser. Always ensure the condition will eventually be false.
Executes at least once, then checks the condition.
do { // code runs AT LEAST once } while (condition); // Example: ask until valid input let input; do { input = prompt("Enter a number > 0:"); } while (input <= 0); // Example: generate random until match let dice; do { dice = Math.ceil(Math.random() * 6); } while (dice !== 6);
while
1. Check condition
2. If true → run body
3. Go to step 1
May run 0 times
do...while
1. Run body
2. Check condition
3. If true → go to step 1
Always runs at least 1 time
// When condition is initially false: let x = 10; while (x < 5) { console.log("while:", x); // never runs } do { console.log("do-while:", x); // runs once! } while (x < 5);
Iterate over values in arrays, strings, maps, and more.
const colors = ["red", "green", "blue"]; for (const color of colors) { console.log(color); } // "red" // "green" // "blue"
Gives you each value directly — no index needed.
💡 for...of works with any iterable: Arrays, Strings, Maps, Sets, generators, NodeLists, etc.
Iterate over object keys (property names).
const user = { name: "Ada", age: 36, city: "London" }; for (const key in user) { console.log(key, "→", user[key]); } // "name" → "Ada" // "age" → 36 // "city" → "London"
⚠️ for...in also iterates over inherited properties. Use Object.keys(obj) for own properties only.
for...of
Iterates values
Arrays, Strings, Maps
for...in
Iterates keys
Objects (properties)
// ⚠️ Don't use for...in with arrays: const arr = ["a", "b", "c"]; for (const i in arr) { console.log(typeof i); // "string" — keys are always strings! } // Use for...of for arrays instead.
A quick decision guide.
| Scenario | Use |
|---|---|
| Known number of iterations | for |
| Unknown iterations, check first | while |
| Must run at least once | do...while |
| Array/iterable values | for...of |
| Object properties | for...in |
💡 In modern JavaScript, for...of and array methods (.forEach(), .map()) are preferred for iterating arrays. Use for when you need the index or complex iteration logic.
Test your understanding.
How many times does this loop run?
for (let i = 0; i < 5; i++) {
console.log(i);
}What is the last value of i printed?
for (let i = 10; i >= 0; i -= 2) {
console.log(i);
}Which loop always runs at least once?
What does for...of iterate over?
Common questions about loops.
Step through the code and watch variables change
1let sum = 0;23for (let i = 1; i <= 3; i++) {4 sum = sum + i;5}67console.log(sum);
No output yetWe declare sum and initialize it to 0.
Test your understanding — 3 questions
How many times will 'hello' be logged?
for (let i = 0; i < 3; i++) {
console.log("hello");
}