for (let i = 1;
i <= 100;
i++) {
console.log("Player " + i);
}JavaScript Loops: Repeating Code with for, while, and Other Loops
Bottom-Line Answer: JavaScript (JS) is a high-level, single-threaded, just-in-time (JIT) compiled programming language with first-class functions that conforms to the ECMAScript specification. It powers dynamic client-side web interactivity alongside HTML and CSS, and executes backend server runtimes via Node.js, Deno, and Bun.
What is JavaScript Loops? Core Concept & Direct Summary
What types of loops are available in JavaScript?
That's the entire superpower of loops:write the instruction once, repeat it as many times as needed.Every animation frame, every search result list, every "load more posts" button on the internet runs on loops.
In this lesson, you'll master all five JavaScript loops —for,while,do…while,for…of, andfor…in— plus the escape hatchesbreakandcontinue, and how to never get trapped in an infinite loop. Let's repeat ourselves… efficiently. 🔁
How Does JavaScript Loops Work? In-Depth Mechanics & Architecture
1️⃣ The for Loop — When You Know How Many Times
Theforloop is the workhorse — the most-used loop in JavaScript. Use it when you know (or can calculate)how many repetitionsyou need.
The Anatomy — Three Parts Inside One Parentheses
Output — watch the flow:
Flexible Counting
The counter is yours to control — count down, skip numbers, whatever you need:
The Classic Combo: for Loop + Array
Looping through arrays by index is the most common real-world pattern:
⚠️ Remember Lesson 5:arrays start at index
0, so the loop runs from0tolength - 1.i < skills.length(not<=) is the safe pattern —<=would run one step too far and printundefined.
2️⃣ The while Loop — When You DON'T Know How Many Times
Awhileloop repeatsas long asits condition stays true — perfect when the endpoint is unpredictable:
Output:
for vs while — The Mental Model
You can't know in advance if the user needs 1 try or 50 — that's whywhileexists.
🚨 The Infinite Loop Trap
If the condition never becomes false, the loop runsforever— freezing the page:
Survival rules:
- Every
whileloop mustchange somethingthat affects its condition - Double-check that the conditioncanbecome false
- When testing new loops, start with small numbers — if it hangs,
Ctrl+C(terminal) or close the tab (browser) and find the missing update
3️⃣ The do…while Loop — Run First, Ask Later
do…whileiswhile's optimistic sibling: italways runs the body at least once, then checks the condition:
Even if the user enters50on the first try, the prompthad to run onceto get that input — which is exactly whydo…whileexists.
while vs do…while
Usedo…whilefor:menus, input prompts, and "try at least once" logic. It's the least-used loop, but unbeatable for these cases.
⚠️ Syntax quirk:
do…whileis the only loop that ends with a semicolon:} while (condition);
4️⃣ The for…of Loop — The Modern Array Walker ⭐
Introduced in ES6,for…ofloops directly over an array'svalues— no counter, no index, nolengthcheck:
Same output, zero bookkeeping. Read it as English:"for each skillofskills…"
It works on strings too (they're iterable — remember Lesson 14's spread!):
Usefor…ofwhen:you need eachitemin an array/string and don't care about positions. This is the modern default for array looping.
5️⃣ The for…in Loop — The Object Walker
for…inloops over an object'skeys(property names):
⚠️ for…of vs for…in — The Famous Interview Question
Golden rule:arrays →for…of; objects →for…in. Mixing them up is a classic beginner bug (and interview trap).
break and continue: The Escape Hatches 🚪
break— Exit the Loop Immediately
continue— Skip Just This Round
🛠️ Mini Project: Multiplication Table Generator ✖️
Output:
Try it yourself:changetableOfto any number, extendupToto 20, or modify the bonus hunt to find results divisible by 3. Loops are learned by playing! 🎮
Which Loop Should You Use? (The Decision Guide)
Honest professional answer: 80% of beginner code uses for and for…of. Master those two first; the others fill specific niches.
Common Beginner Mistakes (And Fixes)
Quick Self-Check: Lesson 17 Quiz 🧠
- What are the three parts of a
forloop's parentheses, and what does each do? - What's the output?
- Which loopalways runs at least once, even if its condition is false?
- What's the output?
- What's the difference between
breakandcontinue?
(Answers: 1. Initialization (create counter), condition (keep going?), update (change counter each round) · 2. 3, 2, 1 — a countdown · 3. do…while — it runs the body first, then checks · 4. H, then I — for…of gives values/characters · 5. break exits the whole loop immediately; continue skips only the current iteration and jumps to the next)
JavaScript Decision Matrix & Syntax Comparison
Understanding the mechanical differences between variable declarations and execution environments is critical for writing performant, bug-free modern JavaScript.
var vs let vs const| Feature / Property | var (Legacy ES5) | let (Modern ES6+) | const (Modern ES6+) |
|---|---|---|---|
| Scope | Function Scope | Block Scope ({}) | Block Scope ({}) |
| Hoisting Behavior | Hoisted (initialized as undefined) | Hoisted (Temporal Dead Zone - ReferenceError) | Hoisted (Temporal Dead Zone - ReferenceError) |
| Reassignable | ✓ Yes | ✓ Yes | ✗ No (Immutable binding) |
| Redeclarable in Same Scope | ✓ Yes (Error-prone) | ✗ No (SyntaxError) | ✗ No (SyntaxError) |
| Window Object Binding | Creates property on window | Does not attach to window | Does not attach to window |
| Dimension | Client-Side (Web Browser) | Server-Side (Node.js / Deno) |
|---|---|---|
| Global Object | window, document, navigator | global, process, globalThis |
| DOM & UI Manipulation | ✓ Full access (document.querySelector) | ✗ No DOM (Headless / Non-UI) |
| File System & OS Access | ✗ Blocked (Sandboxed security) | ✓ Full access (fs, os, child_process) |
| Primary Focus | Interactive UI, animations, client state | REST APIs, microservices, databases, I/O streaming |
Runnable JavaScript Code Example & Practical Implementation
let colors =['red', 'green', 'blue'];
for (let color of colors) {
console.log(color);
}let person = {
name: 'John', age: 30
};
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}Frequently Asked Questions & Technical Interview Insights
Technical Interview & Viva Questions
Frequently asked questions for frontend & full-stack rolesQ: Why should you avoid using for...in to iterate over Arrays?
Related Tools, Tutorials & Authoritative References
Recommended Interactive Tools
- Online JavaScript Editor & IDE — Browser-based JavaScript workspace with live console and DOM inspector.
- C Programming Tutorial — Master memory allocation, pointers, and systems programming fundamentals.
- C++ Programming Tutorial — Explore Object-Oriented Programming, templates, and high-performance STL.
- Online Code Editors & Compilers — Complete development tool suite for 20+ programming languages.
Authoritative Standards & Citations
- ECMA-262 ECMAScript Language Specification — The official international JavaScript language specification maintained by TC39.
- MDN Web Docs (Mozilla Developer Network) — Authoritative documentation and API guide for JavaScript and Web APIs.
- Google V8 JavaScript Engine — Open-source high-performance JavaScript and WebAssembly engine documentation.
- Node.js Official Documentation — Server-side JavaScript runtime API specification and reference.