Site icon ni18 Blog

JavaScript Loops and Iterations

Imagine you’re playing a game where you tell a friend, “Take five steps east, then three steps north.” You could repeat those instructions over and over—or you could use a shortcut. In programming, that shortcut is called a loop. Loops are like a magic trick: they let you repeat tasks without writing the same code a million times. In JavaScript, loops are a big deal because they save time, make code cleaner, and handle all kinds of repetitive jobs.

In this guide, we’ll explore what loops are, why they’re so powerful, and how to use them in JavaScript. We’ll cover the different types—like for, while, and more—plus some cool tricks like break and continue. By the end, you’ll be ready to use loops in your own projects. Let’s get looping!


What Are Loops in Programming?

Picture this: you’re building a robot to pick up toys. Instead of saying “pick up toy one, pick up toy two, pick up toy three,” you could just say, “pick up toys five times.” That’s what loops do—they repeat a task for you. In JavaScript, a loop is a way to run a chunk of code over and over, either a set number of times or until a condition changes.

Here’s a simple example:

for (let i = 0; i < 5; i++) {
  console.log("Take a step to the east");
}

This code prints “Take a step to the east” five times. Without a loop, you’d have to write that line five times—boring and messy!

Why Loops Are Awesome

Now, let’s meet the different types of loops JavaScript offers!


Types of Loops in JavaScript

JavaScript has several loop styles, each with its own superpower. Whether you know exactly how many times to loop or just want to keep going until something happens, there’s a loop for you. Here’s the lineup:

1. The for Loop: The Countdown Champion

The for loop is the go-to when you know how many times you want to repeat something. It’s like setting a timer: “Do this 5 times, then stop.”

  for (let i = 0; i < 5; i++) {
    console.log("Step " + i);
  }
  for (let i = 0; i < 3; i++) {
    console.log("Take a step north");
  }

Prints “Take a step north” three times.

2. The while Loop: The “Keep Going” Guy

The while loop keeps running as long as a condition is true. It’s like saying, “Keep dancing until the music stops.”

  let i = 0;
  while (i < 5) {
    console.log("Dance move " + i);
    i++;
  }

3. The do...while Loop: The “Try Once” Twist

This one’s like while, but it always runs at least once because it checks the condition after the code runs.

  let i = 0;
  do {
    console.log("Wave " + i);
    i++;
  } while (i < 5);

4. The for...in Loop: The Object Explorer

This loop is for snooping through an object’s properties (like keys in a dictionary).

  const obj = { a: 1, b: 2, c: 3 };
  for (const key in obj) {
    console.log(key + ": " + obj[key]);
  }

5. The for...of Loop: The List Lover

This one loops through items in arrays, strings, or other “iterable” things (think lists you can step through).

  const arr = [10, 20, 30];
  for (const value of arr) {
    console.log(value);
  }

Loop Control: break and continue

Sometimes you need to boss your loops around. That’s where break and continue come in—they’re like remote controls for your loops.

break: The Emergency Exit

break stops a loop dead in its tracks.

  for (let i = 0; i < 10; i++) {
    if (i === 5) break;
    console.log(i);
  }

continue: The Skip Button

continue skips the current loop and moves to the next one.

  for (let i = 0; i < 5; i++) {
    if (i === 2) continue;
    console.log(i);
  }

Labeled Loops: The Boss Level

For extra control, you can add labels to loops. A label is just a name (like outerLoop:) that lets you target a specific loop with break or continue. It’s handy in nested loops (loops inside loops).

  outerLoop: for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
      if (i === 1 && j === 1) break outerLoop;
      console.log("i=" + i + ", j=" + j);
    }
  }

Loops in Action: Real-World Examples

Let’s see loops solve some fun problems!

Example 1: Game Directions

for (let i = 0; i < 5; i++) {
  console.log("Take a step east");
}
for (let i = 0; i < 3; i++) {
  console.log("Take a step north");
}

Example 2: Countdown Timer

let time = 5;
while (time > 0) {
  console.log(time + " seconds left");
  time--;
}

Example 3: Shopping List

const items = ["milk", "bread", "eggs"];
for (const item of items) {
  console.log("Buy " + item);
}

Comparing Loops: Which One to Pick?

Here’s a quick table to help you choose:

Loop TypeBest ForRuns at Least Once?Needs a Counter?
forKnown number of repeatsNoYes
whileCondition-based repeatsNoSometimes
do...whileAt least one runYesSometimes
for...inObject propertiesNoNo
for...ofArrays or iterablesNoNo

Tips for Loop Mastery

  1. Start Simple: Try a for loop to print numbers first.
  2. Watch for Infinite Loops: Forgot i++? Your loop might never stop!
  3. Mix and Match: Use break or continue to tweak behavior.
  4. Practice: Build a small project—like a countdown or list printer.

Conclusion: Loops Are Your Coding Superpower

Loops in JavaScript are like a trusty sidekick—they handle the boring, repetitive stuff so you can focus on the fun parts of coding. Whether it’s a for loop counting steps, a while loop waiting for something, or a for...of loop strolling through an array, each one has a job to do. Add in break, continue, and labels, and you’ve got total control.

Exit mobile version