Topic 17 of 59 JavaScript Decision Making & Control Flow Interactive Tutorial

JavaScript Loops: Repeating Code with for, while, and Other Loops

23 mins read Last updated: 22 Aug 2026 14453 views
Quick Summary & Key Takeaway Target Skill Level: Beginner to Advanced ES6+

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.

Target Audience: Frontend developers, full-stack engineers, students & QA testers.
Prerequisites: Basic HTML semantics & fundamental CSS styling rules.
Primary Use Cases: Dynamic web UI, DOM manipulation, asynchronous REST APIs, Node.js backend services.

What is JavaScript Loops? Core Concept & Direct Summary

Core Objective & Problem Statement

What types of loops are available in JavaScript?

Direct Answer Summary
JS provides standard for loops, while loops, do...while loops, for...in (for object keys), and for...of (for iterable values).

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. 🔁

script.js
Run Online
for (let i = 1;
i <= 100;
i++) {
  console.log("Player " + i);
}

How Does JavaScript Loops Work? In-Depth Mechanics & Architecture

for...of iterates over values of array/string/Set/Map iterables. for...in iterates over enumerable string property keys of an object.

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

script.js
Run Online
for (let i = 1;
i <= 5;
i++) {
  console.log("Iteration " + i);
}
script.js
Run Online
for ( ①start;
②condition;
③update) {
  ④ code block that repeats
}
PartCodeJobWhen It Runs
① Initializationlet i = 1Creates the counterOnce, at the start
② Conditioni <= 5"Keep going?"Beforeeveryrepetition
③ Updatei++Changes the counterAftereveryrepetition
④ Body{ console.log… }The repeated taskEach time condition is true

Output — watch the flow:

script.js
Run Online
Iteration 1 ← i=1, 1<=5 true, run body, then i++Iteration 2 ← i=2, 2<=5 true, run body, then i++Iteration 3Iteration 4Iteration 5 ← i=5, 5<=5 true, run body, then i++ ← i=6, 6<=5 FALSE → loop exits ✅

Flexible Counting

The counter is yours to control — count down, skip numbers, whatever you need:

script.js
Run Online
// Countdown 🚀for (let i = 5; i >= 1; i--) {  console.log(i);}console.log("Liftoff!");// 5, 4, 3, 2, 1, Liftoff!
// Even numbers onlyfor (let i = 2; i <= 10; i += 2) {  console.log(i);}// 2, 4, 6, 8, 10

The Classic Combo: for Loop + Array

Looping through arrays by index is the most common real-world pattern:

script.js
Run Online
let skills =["HTML", "CSS", "JavaScript", "React"];
for (let i = 0;
i < skills.length;
i++) {
  console.log(`${i + 1}. ${skills[i]}`);
}//
1. HTML//
2. CSS//
3. JavaScript//
4. React

⚠️ Remember Lesson 5:arrays start at index0, 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:

script.js
Run Online
let battery = 100;
while (battery > 20) {
  console.log(`Battery: ${battery}% — keep gaming 🎮`);
  battery -= 30;
}console.log(`Battery: ${battery}% — charge me! 🔌`);

Output:

script.js
Run Online
Battery: 100% — keep gaming 🎮Battery: 70% — keep gaming 🎮Battery: 40% — keep gaming 🎮Battery: 10% — charge me! 🔌

for vs while — The Mental Model

forwhile
Know the count in advance?✅ Yes❌
Repeat untilsomething happens?✅ Yes
Real-world example"Print 100 names""Keep asking until password is correct"
script.js
Run Online
// The while loop's home turf — unpredictable endings:let attempts = 0;let password = "";
while (password !== "secret123") {
  password = prompt("Enter password:");
  attempts++;
}console.log(`Unlocked after ${attempts} attempts! 🔓`);

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:

script.js
Run Online
// 💀 DANGER — battery never decreases:while (battery > 20) {
console.log("Playing…");
// forgot battery -= 30; — INFINITE LOOP!
}

Survival rules:

  1. Everywhileloop mustchange somethingthat affects its condition
  2. Double-check that the conditioncanbecome false
  3. 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:

script.js
Run Online
let number;
do {
  number = Number(prompt("Enter a number above 10:"));
} while (number <= 10);
console.log(`Thanks! ${number} works ✅`);

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

script.js
Run Online
let x = 100;
// while — checks FIRST (may never run)while (x < 10) {  console.log("while ran");       // never runs — 100 < 10 is false}
// do…while — runs FIRST (always at least once)do {  console.log("do…while ran!");   // runs once, THEN checks} while (x < 10);

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:

script.js
Run Online
let skills =["HTML", "CSS", "JavaScript"];
// Old way 😴
for (let i = 0;
i < skills.length;
i++) {
  console.log(skills[i]);
}// for…of way ✨
for (let skill of skills) {
  console.log(skill);
}

Same output, zero bookkeeping. Read it as English:"for each skillofskills…"

It works on strings too (they're iterable — remember Lesson 14's spread!):

script.js
Run Online
for (let letter of "JS") {
  console.log(letter);
}// J
// S

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):

script.js
Run Online
let student = {
  name: "Riya", age: 22, grade: "A"
};
for (let key in student) {
  console.log(`${key}: ${student[key]}`);
}// name: Riya
// age: 22
// grade: A

⚠️ for…of vs for…in — The Famous Interview Question

for…offor…in
Loops overValuesKeys/indexes
Built forArrays, strings, iterablesObjects
for (x of ["a","b"])x="a","b"—
for (x in ["a","b"])—x="0","1"(indexes as strings!)
script.js
Run Online
let letters =["a", "b"];
for (let x of letters) console.log(x);
// "a" "b" — VALUES
for (let x in letters) console.log(x);
// "0" "1" — INDEXES 😮

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

script.js
Run Online
// Find the first even number, then STOP
let numbers =[1, 3, 7, 8, 9, 12];
for (let num of numbers) {
  if (num % 2 === 0) {
    console.log(`Found an even number: ${num} ✅`);
    break;
    // exit NOW — don't waste time on the rest
  }
}// Found an even number: 8 ✅   (9 and 12 never checked)

continue— Skip Just This Round

script.js
Run Online
// Print only odd numbers — skip the evens
for (let i = 1;
i <= 6;
i++) {
  if (i % 2 === 0) {
    continue;
    // skip evens, jump to next iteration
  } console.log(i);
}// 1, 3, 5
KeywordEffectAnalogy
breakExits theentire loop🚪 Leaving the cinema mid-movie
continueSkips to thenext iteration⏭️ Skipping one song in a playlist

🛠️ Mini Project: Multiplication Table Generator ✖️

script.js
Run Online
// ✖️ Multiplication Table — nested loops in action!
let tableOf = 7;
let upTo = 10;
console.log(`=== Table of ${tableOf} ===`);
for (let i = 1;
i <= upTo;
i++) {
  let result = tableOf * i;
  console.log(`${tableOf} × ${i} = ${result}`);
}// Bonus: find the first result above 50, then stop
console.log("\n=== Bonus Hunt ===");
for (let i = 1;
i <= upTo;
i++) {
  let result = tableOf * i;
  if (result > 50) {
    console.log(`First result above 50: ${tableOf} × ${i} = ${result} 🎯`);
    break;
  }
}

Output:

script.js
Run Online
=== Table of 7 ===7 × 1 = 77 × 2 = 14…7 × 10 = 70=== Bonus Hunt ===First result above 50: 7 × 8 = 56 🎯

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)

Architecture Diagram
Need to repeat code?
│
├─ Know how many times? ──YES──► for loop
│
├─ Repeat until something changes? ──YES──► while
│   └─ Must run at least once? ──YES──► do…while
│
├─ Walking through an array's values? ──YES──► for…of ⭐
│
└─ Walking through an object's keys? ──YES──► for…in

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)

❌ Mistake🔍 What Happens✅ Fix
for (let i = 0; i <= arr.length; i++)One step too far → printsundefinedi < arr.length
Forgettingi++in a while loopInfinite loop— page freezes 💀Always update the condition variable
for (let i in arr)thenarr[i] + 1iis astringindex → "01" 😱Usefor…offor array values
while (x < 10);with semicolonEmpty infinite loop 😱No;after the condition (except do…while!)
Modifying an array while looping itSkipped/duplicated itemsLoop a copy:[...arr](Lesson 14!)
Usingfor…inon objects expecting valuesGets keys like"name", not"Riya"Access withobj[key]inside the loop

Quick Self-Check: Lesson 17 Quiz 🧠

  1. What are the three parts of aforloop's parentheses, and what does each do?
  2. What's the output?
    script.js
    Run Online
    for (let i = 3;
    i >= 1;
    i--) {
      console.log(i);
    }
  3. Which loopalways runs at least once, even if its condition is false?
  4. What's the output?
    script.js
    Run Online
    for (let letter of "HI") {
      console.log(letter);
    }
  5. What's the difference betweenbreakandcontinue?

(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.

Variable Declarations: var vs let vs const
Feature / Propertyvar (Legacy ES5)let (Modern ES6+)const (Modern ES6+)
ScopeFunction ScopeBlock Scope ({})Block Scope ({})
Hoisting BehaviorHoisted (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 BindingCreates property on windowDoes not attach to windowDoes not attach to window
Environment Decision Matrix: Browser Client-Side vs Node.js Server-Side
DimensionClient-Side (Web Browser)Server-Side (Node.js / Deno)
Global Objectwindow, document, navigatorglobal, 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 FocusInteractive UI, animations, client stateREST APIs, microservices, databases, I/O streaming

Runnable JavaScript Code Example & Practical Implementation

script.js
Run Online
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 roles
Q

Q: Why should you avoid using for...in to iterate over Arrays?

A: for...in iterates over all enumerable properties (including custom prototype properties) and does not guarantee numeric index order.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations