Iterative control instructions in Javascript

  • Iterative control instructions, also known as loops, are used in JavaScript to execute a set of statements repeatedly until a certain condition is met. These instructions help in reducing the amount of code required for repetitive tasks and make the code more efficient. In JavaScript, there are three types of loops available: for, while, and do-while.
  • For Loop: A for loop is used when the number of iterations is known. It consists of three parts: initialization, condition, and increment/decrement. The initialization statement is executed only once at the beginning of the loop. The condition statement is checked before each iteration, and if it evaluates to true, the loop executes. The increment/decrement statement is executed at the end of each iteration.

    for (var i = 0; i < 10; i++) {
        console.log(i);
    }

  • While Loop: A while loop is used when the number of iterations is unknown. It consists of a condition statement that is checked before each iteration, and if it evaluates to true, the loop executes.

    var i = 0;
    while (i < 10) {
        console.log(i);
        i++;
    }

  • Do-While Loop: A do-while loop is similar to a while loop, but it executes at least once, even if the condition is false. It consists of a block of statements and a condition statement that is checked after each iteration.

    var i = 0;
    do {
        console.log(i);
        i++;
    } while (i < 10);

  • In addition to these three loops, JavaScript also has the for...in and for...of loops, which are used to iterate over the properties of an object and the values of an iterable object, respectively.
  • For...in Loop: The for...in loop is used to iterate over the properties of an object. It works by iterating over all the enumerable properties of an object.

    var person = { name: "John", age: 30, city: "New York" };
    for (var property in person) {
        console.log(property + ": " + person[property]);
    }

  • For...of Loop: The for...of loop is used to iterate over the values of an iterable object such as an array, a string, or a set.

    var fruits = ["apple", "banana", "mango"];
    for (var fruit of fruits) {
        console.log(fruit);
    }

  • In conclusion, iterative control instructions, or loops, are a fundamental aspect of JavaScript programming that enable the execution of repetitive tasks with minimal code. By understanding the different types of loops available in JavaScript, developers can write more efficient and effective code.

No comments:

Post a Comment