"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

Control Flow

 

Control flow determines the order in which statements are executed in a program. JavaScript provides several structures to make decisions and repeat actions.


Conditional Statements: if, else, else if

Conditional statements let you run code only if certain conditions are met.

let age = 20;

 

if (age < 18) {

  console.log("You are a minor.");

} else if (age >= 18 && age < 65) {

  console.log("You are an adult.");

} else {

  console.log("You are a senior.");

}


switch Statement

The switch statement is used when you need to compare a value against multiple possible matches.

let day = "Monday";

 

switch (day) {

  case "Monday":

    console.log("Start of the week!");

    break;

  case "Friday":

    console.log("Almost weekend!");

    break;

  case "Saturday":

  case "Sunday":

    console.log("Weekend!");

    break;

  default:

    console.log("Midweek day.");

}


Loops: for, while, do...while

Loops let you execute code repeatedly while a condition is true.

For Loop – repeats code a specific number of times:

for (let i = 1; i <= 5; i++) {

  console.log(i);

}

While Loop – runs as long as the condition is true:

let i = 1;

while (i <= 5) {

  console.log(i);

  i++;

}

Do...While Loop – runs the code at least once, then repeats while the condition is true:

let i = 1;

do {

  console.log(i);

  i++;

} while (i <= 5);


break and continue

  • break stops the loop entirely.
  • continue skips the current iteration and moves to the next.

for (let i = 1; i <= 5; i++) {

  if (i === 3) {

    continue; // Skip number 3

  }

  if (i === 5) {

    break; // Stop loop at 5

  }

  console.log(i);

}

 

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)