Index

Loops and Iteration

JavaScript for Beginners

6.1 for, while, and do...while Loops

Loops are fundamental in JavaScript for running the same block of code multiple times. The three main types — for, while, and do...while — each have their own syntax and best use cases.

for Loop

The for loop is great when you know how many times you want to run the loop, such as counting up or down.

Syntax:

for (initialization; condition; update) {
  // code to run
}

Example: Counting up from 1 to 5

for (let i = 1; i <= 5; i++) {
  console.log(i);
}
// Output: 1 2 3 4 5

Example: Counting down from 5 to 1

for (let i = 5; i >= 1; i--) {
  console.log(i);
}
// Output: 5 4 3 2 1

while Loop

Use a while loop when you want to run code as long as a condition remains true, but you might not know in advance how many times it will run.

Syntax:

while (condition) {
  // code to run
}

Example: Counting up until a condition changes

let count = 1;
while (count <= 5) {
  console.log(count);
  count++;
}
// Output: 1 2 3 4 5

do...while Loop

The do...while loop guarantees the code inside runs at least once, then continues as long as the condition is true.

Syntax:

do {
  // code to run
} while (condition);

Example: Run code once, then repeat while condition holds

let count = 1;
do {
  console.log(count);
  count++;
} while (count <= 5);
// Output: 1 2 3 4 5

When to Use Each Loop

Understanding these loops lets you handle many repetitive tasks efficiently, from counting and iterating over data to waiting for certain conditions in your program.

Index

6.2 break and continue

When working with loops, sometimes you want to control the flow more precisely—either stop the loop early or skip certain iterations. JavaScript provides two keywords to help with this: break and continue.

break — Exit the Loop Early

The break statement immediately stops the entire loop and exits it, no matter where it is in the loop cycle.

Example: Exit loop when a specific number is found

for (let i = 1; i <= 10; i++) {
  if (i === 5) {
    console.log("Number 5 found, stopping loop.");
    break;  // Exit loop here
  }
  console.log(i);
}

// Output:
// 1
// 2
// 3
// 4
// Number 5 found, stopping loop.

In this example, the loop stops as soon as it reaches number 5.

continue — Skip the Current Iteration

The continue statement skips the rest of the code in the current loop iteration and immediately moves to the next one.

Example: Skip even numbers in a range

for (let i = 1; i <= 10; i++) {
  if (i % 2 === 0) {
    continue;  // Skip even numbers
  }
  console.log(i);
}

// Output: 1 3 5 7 9

Here, whenever the number is even, continue skips the console.log(i) statement, so only odd numbers are printed.

Summary

These control statements give you flexible ways to manage loops, making your code more efficient and easier to read.

Index

6.3 Looping Patterns (Countdowns, Accumulators)

Loops are powerful tools that let you repeat tasks efficiently. Here are some common patterns you’ll encounter when working with loops, along with clear examples.

Accumulator Pattern: Summing Numbers

An accumulator keeps a running total (or result) that updates each time the loop runs. This is useful for adding up numbers or combining data.

let sum = 0; // Initialize accumulator

for (let i = 1; i <= 5; i++) {
  sum += i; // Add current number to sum
}

console.log("Sum of numbers 1 to 5 is:", sum);
// Output: Sum of numbers 1 to 5 is: 15

Countdown Timer

Loops can also count down from a starting number to zero, useful for timers or countdown displays.

let countdown = 5;

while (countdown > 0) {
  console.log("Countdown:", countdown);
  countdown--; // Decrement the counter
}

console.log("Liftoff!");
// Output:
// Countdown: 5
// Countdown: 4
// Countdown: 3
// Countdown: 2
// Countdown: 1
// Liftoff!

Building a New Array

You can use loops to create or transform arrays by adding items one by one.

let numbers = [1, 2, 3, 4, 5];
let squares = []; // Empty array to store results

for (let i = 0; i < numbers.length; i++) {
  squares.push(numbers[i] * numbers[i]); // Square each number and add to new array
}

console.log("Squares:", squares);
// Output: Squares: [1, 4, 9, 16, 25]

Summary

These patterns are essential building blocks for solving many programming problems and will help you write efficient, readable code.

Index