JavaScript and TypeScript course ยท Module 1: JavaScript Basics

Loops and Iterations

13 min read ยท
In this lesson11

In Jurassic Park, routine tasks must be performed regularly and repeatedly: checking the fence of every enclosure every hour, monitoring all security cameras, updating the health status of every dinosaur. Performing these tasks manually would be tedious and error-prone.

Similarly in JavaScript, loops allow for the automatic and efficient execution of repetitive operations. Instead of writing the same code multiple times, we can use loops to execute it for many elements or a specified number of times.

The for Loop

The for loop is one of the most popular loops in JavaScript. It consists of three parts: initialization, condition, and update expression.

// Basic structure of the for loop
for (initialization; condition; update) {
  // Code block to execute
}

In practice in Jurassic Park, we can use the for loop to automate routine tasks:

// Checking the health of every dinosaur in a sector
let dinosaurs = ["Tyrannosaurus", "Velociraptor", "Triceratops", "Stegosaurus", "Brachiosaurus"];

for (let i = 0; i < dinosaurs.length; i++) {
  console.log(`Checking health status: ${dinosaurs[i]}`);
  // Code to check the health of a specific dinosaur...
}

// Result:
// Checking health status: Tyrannosaurus
// Checking health status: Velociraptor
// Checking health status: Triceratops
// Checking health status: Stegosaurus
// Checking health status: Brachiosaurus

// Security camera monitoring
for (let camera = 1; camera <= 10; camera++) {
  console.log(`Checking camera #${camera}`);
  // Code to analyze the camera feed...
}

// Generating a daily report for the last 7 days
for (let day = 1; day <= 7; day++) {
  console.log(`Generating report for day #${day}`);
  // Code to generate the report for a specific day...
}

The for loop has three main elements:

  1. Initialization (e.g., let i = 0) - executed once, before the loop starts
  2. Condition (e.g., i < dinosaurs.length) - checked before each iteration; the loop ends when the condition returns false
  3. Update (e.g., i++) - executed after each iteration

The for...of Loop

The for...of loop is a newer and more elegant form of loop that allows iterating over elements of a collection (arrays, strings, maps, sets, etc.) without the need to track indices.

// Structure of the for...of loop
for (let element of collection) {
  // Code block to execute for each element
}

The for...of loop is particularly useful when we're interested in the elements themselves, not their indices:

// Checking the health of each dinosaur using for...of
let dinosaurs = ["Tyrannosaurus", "Velociraptor", "Triceratops", "Stegosaurus", "Brachiosaurus"];

for (let dinosaur of dinosaurs) {
  console.log(`Checking health status: ${dinosaur}`);
  // Code to check the health of a specific dinosaur...
}

// Checking food supply levels for different food types
let foodSupplies = {
  meat: 500, // kg
  leaves: 1200, // kg
  fruit: 300, // kg
  fish: 200 // kg
};

// Note: for...of doesn't work directly on objects, but we can use Object.entries()
for (let [foodType, amount] of Object.entries(foodSupplies)) {
  console.log(`Food: ${foodType}, Amount: ${amount} kg`);

  if (amount < 300) {
    console.log(`WARNING: Low supply of ${foodType}! Needs restocking.`);
  }
}

// Result:
// Food: meat, Amount: 500 kg
// Food: leaves, Amount: 1200 kg
// Food: fruit, Amount: 300 kg
// Food: fish, Amount: 200 kg
// WARNING: Low supply of fish! Needs restocking.

The for...in Loop

The for...in loop is designed for iterating over the properties of an object. It returns the names of keys (properties) of the object.

// Structure of the for...in loop
for (let key in object) {
  // Code block to execute for each key
}

Example use in Jurassic Park:

// Analyzing dinosaur data
let tyrannosaurus = {
  species: "Tyrannosaurus Rex",
  age: 12,
  weight: 8000, // kg
  length: 12, // m
  height: 5.6, // m
  speed: 27, // km/h
  aggressionLevel: "Very high"
};

// Displaying all information about the dinosaur
for (let trait in tyrannosaurus) {
  console.log(`${trait}: ${tyrannosaurus[trait]}`);
}

// Checking which dinosaur traits exceed safety values
let safetyLimits = {
  weight: 5000, // kg
  speed: 25, // km/h
  aggressionLevel: "High"
};

for (let parameter in safetyLimits) {
  if (tyrannosaurus[parameter] > safetyLimits[parameter] ||
      (parameter === "aggressionLevel" && tyrannosaurus[parameter] === "Very high")) {
    console.log(`WARNING: Parameter ${parameter} exceeds safety values!`);
  }
}

// Result:
// WARNING: Parameter weight exceeds safety values!
// WARNING: Parameter speed exceeds safety values!
// WARNING: Parameter aggressionLevel exceeds safety values!

Important note: The for...in loop iterates over all properties of an object, including inherited ones. If we want to limit ourselves to only the object's own properties, we can use the hasOwnProperty() method:

for (let trait in tyrannosaurus) {
  if (tyrannosaurus.hasOwnProperty(trait)) {
    console.log(`${trait}: ${tyrannosaurus[trait]}`);
  }
}

Differences Between for...of and for...in

It's important to understand the difference between these two types of loops:

  • for...of - iterates over values of collection elements (arrays, strings, etc.)
  • for...in - iterates over property names (keys) of an object
let dinosaurNames = ["T-Rex", "Raptor", "Triceratops"];

// for...of (values)
for (let name of dinosaurNames) {
  console.log(name); // "T-Rex", "Raptor", "Triceratops"
}

// for...in (indices/keys)
for (let index in dinosaurNames) {
  console.log(index); // "0", "1", "2"
  console.log(dinosaurNames[index]); // "T-Rex", "Raptor", "Triceratops"
}

The while Loop

The while loop executes a block of code as long as a specified condition is true. Unlike the for loop, the while loop only has a condition.

// Structure of the while loop
while (condition) {
  // Code block to execute
}

In Jurassic Park, the while loop can be used for processes that don't have a predetermined number of iterations:

// Egg incubator temperature monitoring system
let temperature = 37.5; // degrees Celsius
let targetTemperature = 38.2;
let temperatureIncrement = 0.1;

console.log("Starting incubator heating process...");

while (temperature < targetTemperature) {
  console.log(`Current temperature: ${temperature.toFixed(1)}ยฐC`);
  temperature += temperatureIncrement;
  // Code to simulate time passing...
}

console.log(`Target temperature reached: ${temperature.toFixed(1)}ยฐC`);

// Power level monitoring system
let powerLevel = 100; // percent
let criticalLevel = 20;
let powerDrop = 5;

console.log("Monitoring power level after main generator failure...");

while (powerLevel > criticalLevel) {
  console.log(`Power level: ${powerLevel}%`);
  powerLevel -= powerDrop;
  // Code to simulate time passing...
}

console.log(`ALARM! Critical power level: ${powerLevel}%`);
console.log("Launching emergency protocol...");

The do...while Loop

The do...while loop is similar to the while loop, but with one key difference: the code block is always executed at least once before the condition is checked.

// Structure of the do...while loop
do {
  // Code block to execute
} while (condition);

This loop is useful when we want the code to execute at least once, regardless of the condition:

// Security system startup procedure
let systemOperational = false;
let attemptCount = 0;
let maxAttempts = 3;

do {
  console.log("Attempting to start the security system...");
  attemptCount++;

  // Simulating random system behavior
  systemOperational = Math.random() > 0.5; // 50% chance of success

  if (systemOperational) {
    console.log("Security system started successfully!");
  } else {
    console.log(`System startup failed. Attempt ${attemptCount} of ${maxAttempts}.`);
  }

} while (!systemOperational && attemptCount < maxAttempts);

if (!systemOperational) {
  console.log("CRITICAL ERROR: Security system cannot be started. Technical intervention required!");
}

// Evacuation procedure
let remainingPeople = 100;

do {
  console.log(`${remainingPeople} people remaining for evacuation.`);
  // Simulation - each iteration represents one evacuated group
  let groupSize = Math.floor(Math.random() * 20) + 10; // 10-29 people
  remainingPeople -= groupSize;

  // Making sure we don't get a negative number
  if (remainingPeople < 0) remainingPeople = 0;

  console.log(`Evacuated a group of ${groupSize} people.`);

} while (remainingPeople > 0);

console.log("Everyone has been evacuated. The facility is empty.");

Breaking and Continuing Loops: break and continue

JavaScript offers two special statements for controlling loop flow:

  • break - immediately stops the loop and exits it
  • continue - stops the current iteration and moves to the next one

Example of Using break

// Searching for a damaged fence section
let fenceSections = [
  { id: 1, status: "intact" },
  { id: 2, status: "intact" },
  { id: 3, status: "damaged" },
  { id: 4, status: "intact" },
  { id: 5, status: "intact" }
];

let damageFound = false;

for (let i = 0; i < fenceSections.length; i++) {
  console.log(`Checking section #${fenceSections[i].id}...`);

  if (fenceSections[i].status === "damaged") {
    console.log(`WARNING! Found damaged section #${fenceSections[i].id}!`);
    console.log("Sending repair team...");
    damageFound = true;
    break; // Stop the loop when we find damage
  }
}

if (!damageFound) {
  console.log("All fence sections are intact.");
}

// Result:
// Checking section #1...
// Checking section #2...
// Checking section #3...
// WARNING! Found damaged section #3!
// Sending repair team...

Example of Using continue

// Checking dinosaur health, skipping those currently under examination
let dinosaurs = [
  { name: "Rex", species: "Tyrannosaurus", available: true },
  { name: "Blue", species: "Velociraptor", available: false }, // Under examination
  { name: "Spike", species: "Stegosaurus", available: true },
  { name: "Cera", species: "Triceratops", available: false }, // Under examination
  { name: "Bronty", species: "Brontosaurus", available: true }
];

console.log("Starting daily health checks...");

for (let i = 0; i < dinosaurs.length; i++) {
  if (!dinosaurs[i].available) {
    console.log(`Dinosaur ${dinosaurs[i].name} (${dinosaurs[i].species}) is already under examination. Skipping.`);
    continue; // Move to the next iteration, skipping the rest of the code in this iteration
  }

  console.log(`Conducting examination of dinosaur ${dinosaurs[i].name} (${dinosaurs[i].species})...`);
  console.log("Examination complete. Health status: good.");
}

// Result:
// Starting daily health checks...
// Conducting examination of dinosaur Rex (Tyrannosaurus)...
// Examination complete. Health status: good.
// Dinosaur Blue (Velociraptor) is already under examination. Skipping.
// Conducting examination of dinosaur Spike (Stegosaurus)...
// Examination complete. Health status: good.
// Dinosaur Cera (Triceratops) is already under examination. Skipping.
// Conducting examination of dinosaur Bronty (Brontosaurus)...
// Examination complete. Health status: good.

Nested Loops

Loops can also be nested inside each other, which is useful when working with multi-dimensional data:

// Checking fence status in all sectors of Jurassic Park

// Two-dimensional array: [sector][fence_section]
let fenceStatus = [
  // Sector 1
  [
    { id: "1A", condition: "intact" },
    { id: "1B", condition: "intact" },
    { id: "1C", condition: "damaged" }
  ],
  // Sector 2
  [
    { id: "2A", condition: "intact" },
    { id: "2B", condition: "intact" },
    { id: "2C", condition: "intact" }
  ],
  // Sector 3
  [
    { id: "3A", condition: "intact" },
    { id: "3B", condition: "damaged" },
    { id: "3C", condition: "intact" }
  ]
];

console.log("Starting fence inspection in all sectors...");

for (let i = 0; i < fenceStatus.length; i++) {
  console.log(`\nInspecting sector ${i + 1}:`);

  let allIntact = true;

  for (let j = 0; j < fenceStatus[i].length; j++) {
    let section = fenceStatus[i][j];
    console.log(`  Section ${section.id}: ${section.condition}`);

    if (section.condition === "damaged") {
      allIntact = false;
      console.log(`  WARNING: Section ${section.id} requires repair!`);
    }
  }

  if (allIntact) {
    console.log(`  All fences in sector ${i + 1} are intact.`);
  } else {
    console.log(`  Damaged fences detected in sector ${i + 1}.`);
  }
}

// Result:
// Starting fence inspection in all sectors...
//
// Inspecting sector 1:
//   Section 1A: intact
//   Section 1B: intact
//   Section 1C: damaged
//   WARNING: Section 1C requires repair!
//   Damaged fences detected in sector 1.
//
// Inspecting sector 2:
//   Section 2A: intact
//   Section 2B: intact
//   Section 2C: intact
//   All fences in sector 2 are intact.
//
// Inspecting sector 3:
//   Section 3A: intact
//   Section 3B: damaged
//   WARNING: Section 3B requires repair!
//   Section 3C: intact
//   Damaged fences detected in sector 3.

Infinite Loops and How to Avoid Them

An infinite loop is a loop that never ends because its termination condition is never met. In Jurassic Park, an infinite loop in the security system could lead to catastrophe, similarly to how in programming it can cause application freezes or consume all resources.

Here's an example of an infinite loop:

// WARNING: This is an infinite loop! Do not run this code!
while (true) {
  console.log("This will display forever!");
}

// Another example of an infinite loop:
for (let i = 0; i >= 0; i++) {
  console.log(i); // This will count forever!
}

To avoid infinite loops:

  1. Make sure the loop termination condition is reachable
  2. Always update the variables used in the loop condition
  3. Consider adding an additional exit condition (e.g., iteration counter)
  4. Use the break statement as a safety measure
// Safer version with iteration limit
let maxIterations = 1000;
let iterationCounter = 0;

// Example of safe monitoring
while (monitorPark()) {
  // Park monitoring code...

  iterationCounter++;
  if (iterationCounter >= maxIterations) {
    console.log("Maximum number of iterations reached. Breaking loop.");
    break;
  }
}

function monitorPark() {
  // Monitoring logic...
  return true; // Normally would return true or false depending on conditions
}

Loop Practices and Patterns

1. Choosing the Right Loop

  • for - when you know the exact number of iterations or work with indices
  • for...of - when you want to iterate over collection elements (arrays, strings)
  • for...in - when you want to iterate over object properties
  • while - when the termination condition depends on external factors
  • do...while - when you want the code to execute at least once

2. Optimizing Loops

// Non-optimal loop - array length is recalculated on each iteration
for (let i = 0; i < dinosaurs.length; i++) {
  // Code...
}

// Optimized loop - array length is calculated only once
for (let i = 0, len = dinosaurs.length; i < len; i++) {
  // Code...
}

3. Early Loop Exit

// Early loop exit after finding the first matching element
function findDinosaur(name) {
  for (let dinosaur of dinosaurDatabase) {
    if (dinosaur.name === name) {
      return dinosaur; // Immediate return upon finding
    }
  }
  return null; // No matching dinosaur
}

4. Avoiding Loop Counter Modification Inside the Loop

// Dangerous - modifying the counter inside the loop
for (let i = 0; i < 10; i++) {
  console.log(i);
  if (i === 5) {
    i = 8; // Skipping some iterations - this can be confusing
  }
}

// Better approach - use continue or break statements
for (let i = 0; i < 10; i++) {
  if (i > 5 && i < 9) {
    continue; // Skip iterations 6, 7, 8
  }
  console.log(i);
}

Summary

Loops in JavaScript, much like routine procedures in Jurassic Park, allow for the efficient execution of repetitive operations:

  1. for - for iterating through a specific number of repetitions
  2. for...of - for iterating over collection elements
  3. for...in - for iterating over object properties
  4. while - for executing code as long as a condition is true
  5. do...while - for executing code at least once, then as long as a condition is true

Additionally, control statements:

  • break - stops the entire loop
  • continue - moves to the next iteration

Choosing the right loop depends on the specific use case, but generally you should aim for:

  • Using the simplest loop appropriate for the task
  • Optimizing loops, especially for large data collections
  • Avoiding infinite loops
  • Using readable variable names and clear code structure

In the next lesson, we will look at functions, which allow organizing code into reusable blocks - essential for maintaining order in such a complex system as Jurassic Park.

Code for this lesson: index.js
// Loops in JavaScript - automating park tasks
// for, while, for...of, for...in

// === for loop ===
console.log("=== for loop: Enclosure patrol ===");

let enclosures = ["T-Rex", "Raptor", "Triceratops", "Brachio", "Stego"];

for (let i = 0; i < enclosures.length; i++) {
  console.log("Enclosure " + (i + 1) + ": " + enclosures[i] + " - OK");
}

// === for loop...of ===
console.log("\n=== for...of: Feeding ===");

for (const dino of enclosures) {
  console.log("Feeding: " + dino);
}

// === for...in loop (for objects) ===
console.log("\n=== for...in: Dinosaur data ===");

const trex = {
  name: "Tyrannosaurus Rex",
  weight: 7000,
  diet: "carnivore",
  sector: "A"
};

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

// === while loop ===
console.log("\n=== while: Scanning samples ===");

let samples = 5;
while (samples > 0) {
  console.log("Scanning sample no. " + samples + "...");
  samples--;
}
console.log("Scanning complete!");

// === do...while ===
console.log("\n=== do...while: Verification ===");

let attempts = 0;
do {
  attempts++;
  console.log("Verification attempt no. " + attempts);
} while (attempts < 3);

// === break and continue ===
console.log("\n=== break and continue ===");

let data = [10, 25, 0, 42, 15, -1, 30];

for (const value of data) {
  if (value === -1) {
    console.log("Found value -1, stopping!");
    break;
  }
  if (value === 0) {
    console.log("Skipping value 0...");
    continue;
  }
  console.log("Processing: " + value);
}

// Your task:
// 1. Use a for loop to print numbers from 1 to 10
// 2. Use while to count down from 10 to 0
// 3. Use for...of to iterate over an array

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What three elements does the for loop header contain?

Hands-on tasks in the game

  • Code editor

    Store the names of at least three enclosures in an array called enclosures. Use a loop to display a message with the name of each enclosure in the console, e.g. 'Checking: T-Rex paddock'.

  • Horizontal ordering

    Arrange the for...of loop elements:

  • Code editor

    Store the species names of DNA samples in an array called dnaSamples, e.g. ['Velociraptor', 'Triceratops', 'Velociraptor']. Go through the array with a loop, count the 'Velociraptor' samples and display the result in the console.

  • Horizontal ordering

    Arrange the for loop elements in the correct order:

  1. Questionfor Loop
  2. Coding taskPractice: Loops
  3. Put in orderfor...of Loop Syntax
  4. Coding taskPractice: Searching the DNA Database
  5. Put in orderfor Loop Syntax

Useful articles