Lesson 20: Mastering JavaScript Loops with challenges!

manoj ymkmanoj ymk
7 min read

Loops are a way to execute a block of code repeatedly based on a condition. In JavaScript, there are several types of loops:

  • while: Loops while the condition is truthy.

  • do...while: Loops at least once before checking the condition.

  • for: Loops with an explicit initialization, condition, and increment/decrement.

Basic Example: for loop

for (let i = 0; i < 3; i++) {
  alert(i); // 0, 1, 2
}

In this loop:

  • begin: The let i = 0 initializes the loop.

  • condition: The condition i < 3 is checked before every iteration.

  • step: The increment i++ happens after the loop body runs.


2. Fill Any Gaps

2.1 break Statement

  • Purpose: The break statement is used to exit a loop immediately, regardless of the loop's condition.

  • Use case: It's often used when we encounter a specific condition inside a loop and no longer need to continue the loop.

Example:

let sum = 0;
while (true) {
  let value = prompt("Enter a number", "");
  if (!value) break; // Exits the loop when no input is given
  sum += Number(value);
}
alert('Sum: ' + sum);

This loop runs indefinitely until the user either cancels or enters an empty value.

2.2 continue Statement

  • Purpose: The continue statement skips the current iteration of the loop and moves to the next one. It doesn't exit the loop entirely, just bypasses the rest of the code in the current iteration.

Example:

for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) continue; // Skip even numbers
  alert(i); // Will alert only odd numbers: 1, 3, 5, 7, 9
}
  • Use case: Use continue when you want to skip processing for certain conditions and continue with the next iteration of the loop.

2.3 Labeled break and continue

  • Purpose: Labeled break and continue allow you to exit or skip specific loops in nested loop structures.

  • Use case: In deeply nested loops, you might want to break or continue an outer loop rather than just the inner loop.

Example (Labeled break):

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    let input = prompt(`Value at coordinates (${i}, ${j})`, "");
    if (!input) break outer; // Breaks out of both loops
    console.log(input);
  }
}
alert('Done!');

In this example, when the user cancels or enters an empty input, the break outer statement stops both loops and exits.

Example (Labeled continue):

outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (j === 1) continue outer; // Continues the outer loop when j === 1
    console.log(`i: ${i}, j: ${j}`);
  }
}

In this case, the continue outer skips the current iteration of the outer loop when j === 1.


3. Challenge Me Deeply

Here are some loop-related challenges with increasing difficulty, from basic to advanced:

๐ŸŸข Basic Challenges:

  1. Basic While Loop: Write a while loop that prints numbers from 1 to 10.

  2. Do-While Loop: Write a do...while loop that continues asking the user for input until they type "exit".

๐ŸŸก Intermediate Challenges:

  1. Nested Loops: Create a multiplication table (10x10) using nested loops.

  2. Skip Even Numbers: Write a loop that skips even numbers from 1 to 20, using the continue statement.

  3. Sum Odd Numbers: Write a while loop that sums the odd numbers from 1 to 100 and stops when the sum exceeds 500.

๐Ÿ”ด Advanced Challenges:

  1. Find Prime Numbers: Write a loop that finds all prime numbers between 1 and 100.

  2. Break Outer Loop: Write a nested loop that asks for coordinates (i, j) from (0,0) to (5,5). Break both loops when the user cancels the prompt.

  3. Infinite Loop with Condition: Create an infinite loop that breaks only when the user enters "stop".

  4. Loop with Object Properties: Write a loop using for...in to list all the keys of an object, but skip keys that contain "admin".

  5. Array Sum and Break Condition: Loop through an array of numbers and calculate the sum. Break when the sum exceeds 100.

๐ŸŽฏ Bonus (Brain-twister):

  • Reverse Fibonacci Sequence: Write a loop that generates the Fibonacci sequence in reverse, starting from a number that you input and stopping when it reaches the first number in the sequence.

4. Interview-Ready Questions

Concept-Based Questions:

  1. What is the difference between while, do...while, and for loops in JavaScript? When would you use each?

  2. Can you explain how the continue and break statements affect the flow of loops?

  3. How does the for...in loop differ from for...of, and what are the cases in which each should be used?

Scenario-Based Questions:

  1. Given a loop with multiple conditions, how would you handle an early exit without using break?

  2. In a nested loop, how can you skip the current iteration of the outer loop without using continue for the inner loop?

Debugging Questions:

  1. What could be the potential issues if an infinite loop is not controlled by a break or condition? How would you debug it?

  2. You are given a loop that runs indefinitely but works perfectly fine in one browser and hangs in another. How would you approach this problem?

Best Practices and Red Flags:

  • Best Practice: Always ensure that the loop condition will eventually evaluate to false to avoid infinite loops.

  • Red Flag: Using break and continue in overly complex nested loops can make the code hard to follow. Try to simplify or refactor such code when possible.


5. Real-World Usage

  • Front-end: Loops are essential in rendering lists, handling user input, or processing dynamic content in web applications. For example, iterating through an array of objects to generate HTML elements dynamically is common.

    • Example: Iterating over a list of items to render them in HTML using for...of:

        const items = ['Item 1', 'Item 2', 'Item 3'];
        let listHTML = '';
        for (const item of items) {
          listHTML += `<li>${item}</li>`;
        }
        document.getElementById('itemList').innerHTML = listHTML;
      
  • Back-end: On the server-side, loops are crucial for processing requests or database records, especially when dealing with large datasets or performing batch processing.

    • Example: In a Node.js app, iterating over a large set of data from a database query to process it before sending a response.
  • Real Libraries/Frameworks: Loops are widely used in libraries like React (rendering lists) or Vue.js (v-for directive to iterate over arrays).


6. Remember Like a Pro

Mnemonics & Analogies:

  • While Loop: Think of a while loop like while driving โ€” you keep going as long as the traffic light is green.

  • Do-While Loop: Imagine do...while as a game where you play once before checking if you should continue โ€” even if you lose on the first try, you play at least once.

  • For Loop: The for loop is like setting up a race with a start, condition to keep going, and a step to progress.

Cheatsheet:

  • break: Exit the loop immediately.

  • continue: Skip the current iteration and proceed to the next one.

  • Labeled break/continue: Skip/break from specific outer loops (good for nested loops).


7. Apply It in a Fun Way

Mini Project: Build a Basic Number Guessing Game

  1. Goal: Use loops to create a number guessing game where the user has to guess the correct number between 1 and 100.

  2. Steps:

    • Display a prompt asking the user to guess a number.

    • Use a loop to check if the guess is correct.

    • Provide feedback: too high, too low, or correct.

    • Allow the user to keep guessing until they get the correct answer.

  3. Code Example:

     let correctNumber = Math.floor(Math.random() * 100) + 1;
     let guess;
     let attempts = 0;
    
     while (guess !== correctNumber) {
       guess = +prompt("Guess the number between 1 and 100:");
       attempts++;
       if (guess < correctNumber) {
         alert("Too low! Try again.");
       } else if (guess > correctNumber) {
         alert("Too high! Try again.");
       }
     }
     alert(`You guessed the number in ${attempts} attempts!`);
    

    Extension: Add a timer to track how long it takes the user to guess the correct number.


8. Optional - Extra Value

  • Advanced Debugging: You can use DevTools to watch loops and add breakpoints at specific iterations to track the variable values dynamically.

  • Optimization: In performance-critical applications, avoid unnecessarily deep nested loops and always ensure the conditions are optimized (e.g., break early to prevent excessive iterations).

0
Subscribe to my newsletter

Read articles from manoj ymk directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

manoj ymk
manoj ymk