Javascript Loop Control

Javascript Loop Control

Loop control in JavaScript refers to the mechanisms used to repeatedly execute a block of code as long as a specified condition is met. JavaScript provides several types of loops to help you iterate over data, repeat actions, or perform calculations.


1. Types of Loops

  • for loop: Runs a block of code a specific number of times.
  • while loop: Repeats as long as a condition is true.
  • do...while loop: Executes the block of code at least once before checking the condition.
  • for...in loop: Iterates over the properties of an object.
  • for...of loop: Iterates over the elements of an iterable object like an array.

  • 2. Loop Detailed Explanation With Examples

    2.1. The for Loop

    The for loop is commonly used for a known number of iterations.

    Example: Print numbers from 1 to 5

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

    Explanation:

    • let i = 1: Initializes the loop variable i.
    • i <= 5: The loop runs while i is less than or equal to 5.
    • i++: Increments i by 1 after each iteration.

    2.2. The while Loop

    The while loop continues as long as the condition is true.

    Example: Print numbers from 1 to 5

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

    Explanation:

    • The loop starts with i = 1.
    • As long as i <= 5, the console.log statement executes.
    • i++ increases i after each iteration.

    2.3. The do...while Loop

    The do...while loop ensures the code runs at least once, even if the condition is false.

    Example: Print numbers from 1 to 5

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

    Explanation:

    • The block inside do executes first.
    • The condition i <= 5 is checked after execution.

    2.4. The for...in Loop

    The for...in loop is used to iterate over the properties of an object.

    Example: Iterate through an object's properties

      let person = { name: "Alice", age: 25, city: "New York" };
      for (let key in person) {
          console.log(`${key}: ${person[key]}`);
      }

    Explanation:

    • key represents each property name.
    • person[key] accesses the value of the property.

    2.5. The for...of Loop

    The for...of loop iterates over iterable objects like arrays, strings, or NodeLists.

    Example: Iterate through an array

      let fruits = ["Apple", "Banana", "Cherry"];
      for (let fruit of fruits) {
          console.log(fruit);
      }

    Explanation:

    • fruit represents each element in the fruits array.
    • The loop prints each fruit.

    4. Summary

    JavaScript loops and control statements are powerful tools for automating repetitive tasks, iterating over data, and managing flow within loops. By combining the different types of loops with break and continue, you can create efficient and readable logic in your programs.

Previous Next