Explore Loop Structures in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

Introduction

In this lab, students will dive deep into JavaScript loop structures, exploring various iteration techniques that are fundamental to programming logic. The lab covers essential loop types including while loops, do-while loops, for loops, and for-in loops, providing hands-on experience with each structure through practical coding examples and incremental learning.

Participants will start by understanding the basic syntax of while loops, learning how to create controlled iterations and perform tasks like counting and conditional searching. As they progress, they'll practice implementing different loop structures, comparing their unique characteristics and use cases, which will help develop a comprehensive understanding of how loops can be used to manipulate data, iterate through arrays, and create dynamic programming solutions in JavaScript.

Understand While Loop Syntax and Basic Usage

In this step, you'll learn about the basic syntax and usage of while loops in JavaScript. While loops are fundamental control structures that allow you to repeat a block of code as long as a specified condition is true.

Let's start by creating a new JavaScript file to explore while loops. Open the WebIDE and create a file named whileLoop.js in the ~/project directory.

// Create a simple while loop to count from 1 to 5
let count = 1;

while (count <= 5) {
  console.log(`Current count: ${count}`);
  count++;
}

Now, run the JavaScript file using Node.js to see the output:

node ~/project/whileLoop.js

Example output:

Current count: 1
Current count: 2
Current count: 3
Current count: 4
Current count: 5

Let's break down the while loop syntax:

  • let count = 1; initializes a counter variable before the loop
  • while (count <= 5) defines the condition that must be true to continue looping
  • console.log() prints the current value of count
  • count++ increments the counter in each iteration

Now, let's create a more practical example that demonstrates a while loop with a more complex condition:

// Create a while loop to find the first number divisible by both 3 and 5
let number = 1;

while (!(number % 3 === 0 && number % 5 === 0)) {
  number++;
}

console.log(`First number divisible by 3 and 5: ${number}`);

Run the file again:

node ~/project/whileLoop.js

Example output:

First number divisible by 3 and 5: 15

This example shows how while loops can be used to search for specific conditions or perform iterative tasks.

Practice Do-While Loop with Incremental Iteration

In this step, you'll learn about do-while loops in JavaScript, which are similar to while loops but with a key difference: the code block is executed at least once before checking the condition.

Create a new file named doWhileLoop.js in the ~/project directory using the WebIDE:

// Demonstrate a do-while loop with user input simulation
let attempts = 0;
let secretNumber = 7;
let guess;

do {
  // Simulate a random guess between 1 and 10
  guess = Math.floor(Math.random() * 10) + 1;
  attempts++;

  console.log(`Attempt ${attempts}: Guessed ${guess}`);

  if (guess === secretNumber) {
    console.log(
      `Congratulations! You guessed the number in ${attempts} attempts.`
    );
  }
} while (guess !== secretNumber);

Run the JavaScript file to see how the do-while loop works:

node ~/project/doWhileLoop.js

Example output:

Attempt 1: Guessed 3
Attempt 2: Guessed 9
Attempt 3: Guessed 7
Congratulations! You guessed the number in 3 attempts.

Key characteristics of do-while loops:

  • The code block is executed at least once before checking the condition
  • The condition is checked at the end of each iteration
  • Useful when you want to ensure the code runs at least once

Let's create another example to further illustrate the do-while loop:

// Demonstrate incremental iteration with do-while loop
let total = 0;
let i = 1;

do {
  total += i;
  console.log(`Current total: ${total}, Current number: ${i}`);
  i++;
} while (total < 10);

console.log(`Final total: ${total}`);

Run the file again:

node ~/project/doWhileLoop.js

Example output:

Current total: 1, Current number: 1
Current total: 3, Current number: 2
Current total: 6, Current number: 3
Current total: 10, Current number: 4
Final total: 10

This example shows how do-while loops can be used for incremental iteration, ensuring the code block runs at least once before checking the termination condition.

Implement For Loop for Controlled Iterations

In this step, you'll learn about for loops in JavaScript, which provide a concise way to perform controlled iterations with a clear start, end, and increment/decrement mechanism.

Create a new file named forLoop.js in the ~/project directory using the WebIDE:

// Basic for loop to print numbers from 1 to 5
console.log("Basic Counting Loop:");
for (let i = 1; i <= 5; i++) {
  console.log(`Current number: ${i}`);
}

// For loop to calculate factorial of a number
console.log("\nFactorial Calculation:");
let number = 5;
let factorial = 1;

for (let j = 1; j <= number; j++) {
  factorial *= j;
}

console.log(`Factorial of ${number} is: ${factorial}`);

// For loop to iterate through an array
console.log("\nArray Iteration:");
let fruits = ["apple", "banana", "cherry", "date"];

for (let k = 0; k < fruits.length; k++) {
  console.log(`Fruit at index ${k}: ${fruits[k]}`);
}

Run the JavaScript file to see the different for loop examples:

node ~/project/forLoop.js

Example output:

Basic Counting Loop:
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5

Factorial Calculation:
Factorial of 5 is: 120

Array Iteration:
Fruit at index 0: apple
Fruit at index 1: banana
Fruit at index 2: cherry
Fruit at index 3: date

Let's break down the for loop syntax:

  • for (initialization; condition; increment/decrement) is the standard structure
  • let i = 1 initializes the loop counter
  • i <= 5 defines the continuation condition
  • i++ increments the counter after each iteration

Create another example demonstrating more complex for loop usage:

// Nested for loop to create a multiplication table
console.log("Multiplication Table:");
for (let row = 1; row <= 5; row++) {
  let rowOutput = "";
  for (let col = 1; col <= 5; col++) {
    rowOutput += `${row * col}\t`;
  }
  console.log(rowOutput);
}

Run the file again:

node ~/project/forLoop.js

Example output:

Multiplication Table:
1	2	3	4	5
2	4	6	8	10
3	6	9	12	15
4	8	12	16	20
5	10	15	20	25

This example shows how nested for loops can be used to create more complex iteration patterns.

Use For-In Loop to Iterate Through Array Elements

In this step, you'll learn about the for-in loop in JavaScript, which provides an easy way to iterate through the properties of an object or elements of an array.

Create a new file named forInLoop.js in the ~/project directory using the WebIDE:

// Iterating through an array using for-in loop
let fruits = ["apple", "banana", "cherry", "date"];

console.log("Iterating through Array Indices:");
for (let index in fruits) {
  console.log(`Index: ${index}, Fruit: ${fruits[index]}`);
}

// Iterating through an object using for-in loop
let student = {
  name: "John Doe",
  age: 22,
  major: "Computer Science",
  gpa: 3.8
};

console.log("\nIterating through Object Properties:");
for (let property in student) {
  console.log(`${property}: ${student[property]}`);
}

// Practical example: Calculating total price of items
let shoppingCart = [
  { name: "Laptop", price: 1000 },
  { name: "Headphones", price: 100 },
  { name: "Mouse", price: 50 }
];

console.log("\nCalculating Total Price:");
let totalPrice = 0;
for (let index in shoppingCart) {
  totalPrice += shoppingCart[index].price;
}
console.log(`Total Price: $${totalPrice}`);

Run the JavaScript file to see the for-in loop in action:

node ~/project/forInLoop.js

Example output:

Iterating through Array Indices:
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry
Index: 3, Fruit: date

Iterating through Object Properties:
name: John Doe
age: 22
major: Computer Science
gpa: 3.8

Calculating Total Price:
Total Price: $1150

Key points about for-in loops:

  • Works with both arrays and objects
  • Iterates through indices (for arrays) or properties (for objects)
  • Provides a simple way to access elements without using traditional index-based loops
  • Be cautious when using with arrays, as it iterates through all enumerable properties

Let's explore another example to demonstrate its flexibility:

// Using for-in loop to filter and transform data
let grades = {
  math: 85,
  science: 92,
  english: 78,
  history: 88
};

console.log("Filtering Grades Above 80:");
for (let subject in grades) {
  if (grades[subject] > 80) {
    console.log(`${subject}: ${grades[subject]}`);
  }
}

Run the file again:

node ~/project/forInLoop.js

Example output:

Filtering Grades Above 80:
math: 85
science: 92
history: 88

Compare and Contrast Different Loop Structures

In this step, you'll explore the differences between various loop structures in JavaScript and learn when to use each type of loop effectively.

Create a new file named loopComparison.js in the ~/project directory using the WebIDE:

// Demonstrating different loop structures for the same task

// 1. While Loop: Best for unknown number of iterations
console.log("While Loop Example:");
let whileCounter = 1;
while (whileCounter <= 5) {
  console.log(`While Loop: ${whileCounter}`);
  whileCounter++;
}

// 2. Do-While Loop: Ensures at least one execution
console.log("\nDo-While Loop Example:");
let doWhileCounter = 1;
do {
  console.log(`Do-While Loop: ${doWhileCounter}`);
  doWhileCounter++;
} while (doWhileCounter <= 5);

// 3. For Loop: Best for known number of iterations
console.log("\nFor Loop Example:");
for (let forCounter = 1; forCounter <= 5; forCounter++) {
  console.log(`For Loop: ${forCounter}`);
}

// 4. For-In Loop: Iterating through object properties
console.log("\nFor-In Loop Example:");
let student = {
  name: "John Doe",
  age: 22,
  major: "Computer Science"
};

for (let property in student) {
  console.log(`${property}: ${student[property]}`);
}

// 5. Comparing Loop Performance
console.log("\nLoop Performance Comparison:");
const iterations = 1000000;

console.time("While Loop");
let a = 0;
while (a < iterations) {
  a++;
}
console.timeEnd("While Loop");

console.time("For Loop");
for (let b = 0; b < iterations; b++) {}
console.timeEnd("For Loop");

Run the JavaScript file to see the comparison:

node ~/project/loopComparison.js

Example output:

While Loop Example:
While Loop: 1
While Loop: 2
While Loop: 3
While Loop: 4
While Loop: 5

Do-While Loop Example:
Do-While Loop: 1
Do-While Loop: 2
Do-While Loop: 3
Do-While Loop: 4
Do-While Loop: 5

For Loop Example:
For Loop: 1
For Loop: 2
For Loop: 3
For Loop: 4
For Loop: 5

For-In Loop Example:
name: John Doe
age: 22
major: Computer Science

Loop Performance Comparison:
While Loop: 2.345ms
For Loop: 1.876ms

Key Differences:

  1. While Loop:

    • Use when number of iterations is unknown
    • Condition checked before each iteration
    • May not execute if condition is false initially
  2. Do-While Loop:

    • Guarantees at least one execution
    • Condition checked after each iteration
    • Useful when you want to run code at least once
  3. For Loop:

    • Best for known number of iterations
    • Compact syntax with initialization, condition, and increment
    • Most commonly used for array iteration and counting
  4. For-In Loop:

    • Specifically for iterating through object properties
    • Works with both objects and arrays
    • Provides index or property names

Let's create a final example to demonstrate choosing the right loop:

// Choosing the right loop for different scenarios
let numbers = [10, 20, 30, 40, 50];

// While loop for conditional search
console.log("\nChoosing the Right Loop:");
let searchValue = 30;
let index = 0;
while (index < numbers.length && numbers[index] !== searchValue) {
  index++;
}
console.log(`Found ${searchValue} at index: ${index}`);

// For loop for simple iteration
console.log("Squared Numbers:");
for (let i = 0; i < numbers.length; i++) {
  console.log(`${numbers[i]} squared: ${numbers[i] * numbers[i]}`);
}

Run the file again:

node ~/project/loopComparison.js

Example output:

Choosing the Right Loop:
Found 30 at index: 2
Squared Numbers:
10 squared: 100
20 squared: 400
30 squared: 900
40 squared: 1600
50 squared: 2500

Summary

In this lab, participants explored various loop structures in JavaScript, focusing on understanding and implementing different types of loops. The lab began with a comprehensive examination of while loops, demonstrating their basic syntax and practical applications through examples that count iterations and search for specific numerical conditions. Participants learned how to initialize loop variables, define loop conditions, and use increment operators to control loop execution.

The lab progressed to cover additional loop types, including do-while loops, for loops, and for-in loops, providing hands-on experience with each structure. By comparing and contrasting these loop mechanisms, learners gained insights into selecting appropriate loop structures for different programming scenarios, enhancing their JavaScript programming skills and understanding of control flow mechanisms.