Loops

Back

Loading concept...

🎢 JavaScript Loops: The Magical Repeat Machine

Imagine you have a toy robot that can do tricks. What if you could tell it: “Do 10 jumping jacks” instead of saying “jump, jump, jump…” ten times? That’s what loops do in JavaScript!


🌟 The Big Picture

Loops are like a magic spell that says: “Do this thing over and over until I say stop.”

Think of it like this:

  • Without loops: “Brush tooth 1, brush tooth 2, brush tooth 3…” (32 times! 😩)
  • With loops: “Brush each tooth once” (done! 🎉)

🔁 The for Loop: The Counter

The for loop is like a counting machine. It knows:

  1. Where to start counting
  2. When to stop
  3. How to count (by 1s, 2s, etc.)

How It Looks

for (let i = 0; i < 5; i++) {
  console.log("Jump number " + i);
}

What’s Happening?

graph TD A["Start: i = 0"] --> B{Is i < 5?} B -->|Yes| C["Do the action"] C --> D["Add 1 to i"] D --> B B -->|No| E["Stop!"]

Breaking it down:

  • let i = 0 → Start at 0
  • i < 5 → Keep going while i is less than 5
  • i++ → Add 1 after each round

Real Example: Counting Stars

for (let star = 1; star <= 5; star++) {
  console.log("⭐".repeat(star));
}

Output:

⭐
⭐⭐
⭐⭐⭐
⭐⭐⭐⭐
⭐⭐⭐⭐⭐

🌀 The while Loop: The Patient Waiter

The while loop is like a patient waiter who keeps asking: “Are we done yet? No? Okay, I’ll do it again.”

How It Looks

let cookies = 5;

while (cookies > 0) {
  console.log("Eating cookie!");
  cookies = cookies - 1;
}

console.log("No more cookies 😢");

When to Use It?

Use while when you don’t know exactly how many times you’ll repeat. Like waiting for rain to stop!

graph TD A["Check condition"] --> B{Is it true?} B -->|Yes| C["Do the action"] C --> A B -->|No| D["Exit loop"]

Real Example: Guessing Game

let secret = 7;
let guess = 0;

while (guess !== secret) {
  guess = getPlayerGuess();
  console.log("Try again!");
}

console.log("You got it! 🎉");

🎯 The do-while Loop: The “At Least Once” Loop

The do-while loop is special. It ALWAYS does the action at least once, then checks if it should repeat.

Think of it like this: You always take at least one bite of food before deciding if you want more!

How It Looks

let dice;

do {
  dice = rollDice();
  console.log("You rolled: " + dice);
} while (dice !== 6);

console.log("Finally got a 6! 🎲");

The Key Difference

Loop Type Checks First? Runs At Least Once?
while ✅ Yes ❌ Maybe not
do-while ❌ No ✅ Always
graph TD A["Do the action first!"] --> B{Check condition} B -->|True| A B -->|False| C["Exit loop"]

🔑 The for-in Loop: The Key Finder

The for-in loop is like a treasure hunter that finds all the keys (property names) in an object.

How It Looks

let pet = {
  name: "Fluffy",
  age: 3,
  type: "cat"
};

for (let key in pet) {
  console.log(key + ": " + pet[key]);
}

Output:

name: Fluffy
age: 3
type: cat

When to Use It?

Use for-in when you want to explore an object and see what’s inside!

graph TD A["Object with keys"] --> B["for-in loop"] B --> C["Gets: name"] B --> D["Gets: age"] B --> E["Gets: type"]

⚠️ Remember: for-in gives you the KEY (the label), not the value!


📦 The for-of Loop: The Value Grabber

The for-of loop is like reaching into a box and pulling out each item one by one. It gives you the values directly!

How It Looks

let fruits = ["🍎", "🍌", "🍇", "🍊"];

for (let fruit of fruits) {
  console.log("I love " + fruit);
}

Output:

I love 🍎
I love 🍌
I love 🍇
I love 🍊

for-in vs for-of: The Big Difference

Loop Works On Gives You
for-in Objects Keys (names)
for-of Arrays, Strings Values (items)

Real Example: Letters in a Word

let word = "HELLO";

for (let letter of word) {
  console.log(letter);
}

Output:

H
E
L
L
O

🛑 break: The Emergency Stop Button

Sometimes you need to STOP a loop immediately. That’s what break does!

Think of it like: Finding your toy in a messy room. Once you find it, you STOP looking!

How It Looks

let numbers = [1, 2, 3, 4, 5, 6, 7];

for (let num of numbers) {
  if (num === 4) {
    console.log("Found 4! Stopping!");
    break;
  }
  console.log(num);
}

Output:

1
2
3
Found 4! Stopping!
graph TD A["Loop running"] --> B{Found what we need?} B -->|No| C["Continue looping"] C --> A B -->|Yes| D["BREAK! Exit now!"]

⏭️ continue: The Skip Button

Sometimes you want to skip ONE round but keep going. That’s continue!

Think of it like: Skipping a song you don’t like, but keeping the playlist going.

How It Looks

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    console.log("Skipping 3!");
    continue;
  }
  console.log("Number: " + i);
}

Output:

Number: 1
Number: 2
Skipping 3!
Number: 4
Number: 5

break vs continue

Command What It Does
break STOP everything! Exit the loop!
continue Skip this round, do the next one
graph TD A["In a loop"] --> B{Special case?} B -->|Use break| C["Exit loop completely"] B -->|Use continue| D["Skip to next round"] D --> A

🎮 Putting It All Together

Here’s when to use each loop:

Loop Best For Example
for Counting a known number of times “Do this 10 times”
while Unknown repeats, check first “Keep going until done”
do-while Must run at least once “Try at least once”
for-in Finding keys in objects “What’s in this object?”
for-of Getting values from arrays “Process each item”

Quick Memory Trick

🔢 for = “I know how many times!” ❓ while = “I’ll check first, then maybe do it” ☝️ do-while = “Do it once, then check” 🔑 for-in = “Find the KEYS” 📦 for-of = “Get the VALUES” 🛑 break = “STOP NOW!” ⏭️ continue = “SKIP this one”


🌈 You Did It!

You now understand all the JavaScript loops! You’re ready to:

  • ✅ Count with for
  • ✅ Wait with while
  • ✅ Try at least once with do-while
  • ✅ Explore objects with for-in
  • ✅ Process arrays with for-of
  • ✅ Stop early with break
  • ✅ Skip rounds with continue

Remember: Loops are your friends. They save you from typing the same thing over and over. Use them wisely, and your code will be shorter, cleaner, and more powerful! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.