Control Flow In JavaScript

 Control flow in JavaScript refers to the order in which statements are executed in a script. It determines how a program progresses from one statement to the next based on conditions and logic. Here's an overview of control flow constructs in JavaScript along with examples:

  1. Conditional Statements:

    • if Statement: It executes a block of code if a specified condition is true.


    • let x = 10; if (x > 5) { console.log("x is greater than 5"); }


    • if...else Statement: It executes one block of code if a specified condition is true and another block if the condition is false.


    • let time = 20; if (time < 18) { console.log("Good day"); } else { console.log("Good evening"); }


    • else if Statement: It provides an alternative condition to check if the first condition is false.


    • let grade = 75; if (grade >= 90) { console.log("A"); } else if (grade >= 80) { console.log("B"); } else if (grade >= 70) { console.log("C"); } else { console.log("D"); }


  2. Looping Statements:

    • for Loop: It repeats a block of code a specified number of times.


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


    • while Loop: It repeats a block of code while a specified condition is true.


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


    • do...while Loop: It repeats a block of code once, and then repeats it as long as a specified condition is true.


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


    • for...in Loop: It iterates over the enumerable properties of an object.


    • const person = {

          name: 'John',

          age: 30,

          gender: 'male'

      };

      for (let key in person) {

          console.log(key + ': ' + person[key]);

      }

       perkey + + person[key]); }

    • for...of Loop: It iterates over the iterable objects like arrays, strings, etc.


    • const fruits = ['apple', 'banana', 'cherry'];

      for (let fruit of fruits) {

          console.log(fruit);

      }


  3. Control Flow Keywords:

    • break: It terminates the current loop or switch statement.
    • continue: It skips the current iteration of a loop and proceeds to the next iteration.

These control flow constructs allow developers to create dynamic and interactive JavaScript applications by controlling the flow of execution based on conditions and looping through data structures.

Post a Comment

0 Comments