Software Development | JavaScript Loops

Loops and Iteration

Overview

Repeating code is a common task in programming. JavaScript provides several loop statements, including for, while, do...while, for...of, and for...in. Each has a specific use case and syntax. Arrays also have a forEach method that calls a function once for each item in the array.

Use for...of to loop over the values of an array. for...in loops over the property names (keys) of an object and is not recommended for arrays.

Prepare

Check Your Understanding

  1. Given the following variable declarations:
    const DAYS = 6;
    const LIMIT = 30;
    const studentReport = [11, 42, 33, 64, 29, 37, 44];
    • Write a for loop that iterates through the studentReport array and prints each value that is below LIMIT to the console.
    • Repeat the first exercise using a while loop.
    • Repeat the first exercise using the forEach method.
    • Repeat the first exercise using a for...of loop.
    • Use any type of loop to produce the day names (Monday, Tuesday, Wednesday, etc.) of the next DAYS days from today's date.
    Check Your Understanding – Example Answers

    These are not the only correct answers.

    // for loop
    for (let i = 0; i < studentReport.length; i++) {
      if (studentReport[i] < LIMIT) {
        console.log(studentReport[i]);
      }
    }
    
    // while loop
    let index = 0;
    while (index < studentReport.length) {
      if (studentReport[index] < LIMIT) {
        console.log(studentReport[index]);
      }
      index++;
    }
    
    // forEach method
    studentReport.forEach((score) => {
      if (score < LIMIT) {
        console.log(score);
      }
    });
    
    // for...of loop
    for (const score of studentReport) {
      if (score < LIMIT) {
        console.log(score);
      }
    }

    Use this CodePen to guide you to a solution for the last exercise. You will need to sift through the example code to find what applies.