JavaScript Notes

Day 8

·

6 min read

Loops in JavaScript

Loops are essential programming constructs that enable us to execute a block of code repeatedly based on a specific condition or a set of conditions. They play a crucial role in automating repetitive tasks and processing large amounts of data efficiently.

while loop

It is generally used when we do not know how many times we want to repeat the code. In this construct, we first check the condition and repeat the piece of code inside the block if and only if the condition is true. The condition can be any statement returning a boolean value of true or false. There is a step of changing the value of the loop variable inside the while block, otherwise, the loop will never break causing a stack overflow exception. Let us see an example of the while loop below.

var a = 10; //loop variable

while(a<10) {//checking the condition
    console.log(a);
    a++: //increment the loop variable
}
💡
Remember, falsy values in JavaScript return false.

do while loop

This construct of the while loop performs the check at the end of the block rather than at the start. It is generally used when we want to perform some task such as user input before checking the condition. The code block executes at least once even if the condition is not satisfied. All the other logic remains the same as the while loop. The below code sample shows an example do while loop which shows the menu selection once, and the user input decides if the loop condition satisfies the condition.

// Sample menu items
const menuItems = [
  "1. View Balance",
  "2. Deposit",
  "3. Withdraw",
  "4. Transfer",
  "5. Quit"
];

// Function to display the menu
function displayMenu() {
  console.log("Menu:");
  for (const item of menuItems) {
    console.log(item);
  }
}

let choice;

do {
    displayMenu();
    choice = window.prompt("Enter your choice (1-5):");

    switch (choice) {
          case "1":
            console.log("Viewing Balance...");
            // Add code here to handle "View Balance" option
            break;
          case "2":
            console.log("Depositing...");
            // Add code here to handle "Deposit" option
            break;
          case "3":
            console.log("Withdrawing...");
            // Add code here to handle "Withdraw" option
            break;
          case "4":
            console.log("Transferring...");
            // Add code here to handle "Transfer" option
            break;
          case "5":
            console.log("Exiting the program. Goodbye!");
            break;
          default:
            console.log("Invalid choice. Please try again.");
            break;
        }
} while(choice !== "5"):

for loop

The for loop consists of three main components, and it follows a defined syntax:

for (initialization; condition; iteration) {
  // Code block to be executed in each iteration
}

It is generally used when we are aware of the number of times to execute the block of code. Let's break down the components of the for loop:

  1. Initialization: This part is executed only once before the loop starts. It is used to initialize a counter variable or set up any other initial conditions. It is optional, and you can declare the counter variable outside the loop as well.

  2. Condition: This part is evaluated before each iteration of the loop. If the condition evaluates to true, the loop continues; if it evaluates to false, the loop terminates, and the program moves to the code after the for loop. If the condition is omitted or left blank, it is considered as true, resulting in an infinite loop unless there's a break statement inside the loop.

  3. Iteration: This part is executed at the end of each iteration and is typically used to update the counter variable or perform any other operations. It is optional, and you can also update the counter variable inside the loop code block.

💡
If you declare a var in the initialization context, the var variable is defined in the function block. So, you cannot initialize the same variable again below.

Let us see an example of the for loop below:

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

Breaking and Skipping a Loop

As seen before, we can exit the loops once the number of iterations is completed or the condition fails. However, there is another way to break out of the loop or skip a particular iteration.

break

The break statement is used to terminate a loop prematurely when a specific condition is met. It allows you to exit the loop immediately, bypassing any remaining iterations that would have occurred naturally.

Here's an example of how the break statement can be used in a for loop:

for (let i = 1; i <= 10; i++) {
  console.log("Loop iteration: " + i);

  if (i === 5) {
    console.log("Breaking out of the loop at iteration 5.");
    break;
  }
}

In this example, the break statement is executed when i is equal to 5. As a result, the loop terminates, and the program continues executing the code after the loop.

continue

The continue statement is used to skip the current iteration of a loop and move on to the next iteration. It allows you to selectively skip some parts of the loop's code block based on a particular condition. When the continue statement is encountered, the loop immediately jumps to the next iteration without executing the remaining code in the current iteration.

Here's an example of how the continue statement works in a for loop:

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    console.log("Skipping iteration " + i);
    continue;
  }
  console.log("Loop iteration: " + i);
}

In this example, when i is equal to 3, the if condition is true, and the continue statement is executed. As a result, the loop skips the console.log("Loop iteration: " + i) statement and moves on to the next iteration. The loop continues to execute for i values from 1 to 5, except when i is 3.

Labelled Statement in JavaScript

A labelled statement is a feature that allows you to associate a label with a specific statement in your code. The label is an identifier followed by a colon (:), and it can be applied to any statement, such as loops or conditional statements. The labelled statement allows you to create a target for break and continue statements to jump to, providing more control over loops or nested loops.

Here is an example:

outerLoop: for (let i = 1; i <= 3; i++) {
  console.log("Outer loop iteration: " + i);

  innerLoop: for (let j = 1; j <= 3; j++) {
    console.log("Inner loop iteration: " + j);

    if (i === 2 && j === 2) {
      break outerLoop;
    }
  }
}

Two other variants of for

for..in

The for...in statement iterates over all enumerable string properties of an object, including inherited enumerable properties.

function Person(name, age, occupation) {
  this.name = name;
  this.age = age;
  this.occupation = occupation;
}

Person.prototype.gender = "Male";

const john = new Person("John Doe", 30, "Engineer");

for (const key in john) {
  console.log(key + ": " + john[key]);
}
//output
/*
name: John Doe
age: 30
occupation: Engineer
gender: Male
*/

As we can see in the above example, the key gender is present in the parent/prototype object still the loop goes through this property. This is one of the major differences between for..in and for..of.

💡
Use object.hasOwnProperty(key) to check if the key belong to the parent/prototype.

for..of

The for...of loop iterates over the values of the iterable object, one by one, without the need for an index or accessing the object's properties.

Let's see an example of using the for...of loop to iterate over an array:

const numbers = [1, 2, 3, 4, 5];

for (const number of numbers) {
  console.log(number);
}
//output
/*
1
2
3
4
5
*/
💡
Use for..of in case of arrays.
Â