Skip to main content

Command Palette

Search for a command to run...

Control Flow in JavaScript

Updated
3 min read

In this article, we learn about the control flow in the programming , why it exists and what are the different ways with which we can handle the control flow of the program.

What is Control Flow?

Control flow refers to the order in which a program executes its instructions.

Normally, JavaScript executes code line by line from top to bottom. But in many situations, we need the program to make decisions and run different code based on conditions.

This is where control flow statements come into play.

Real-Life Example

Imagine deciding what to wear:

If it is raining → take an umbrella
Else → wear sunglasses

if statement

The if statement is used when we want to execute code only if a condition is true.

Syntax

if (condition) {
  // code runs if condition is true
}

Example

let age = 20;

if (age >= 18) {
  console.log("You can vote");
}

if...else Statement

Sometimes we want to run one block of code if the condition is true and another block if it is false.

Syntax

if (condition) {
  // runs if condition is true
} else {
  // runs if condition is false
}
let age = 16;

if (age >= 18) {
  console.log("You can vote");
} else {
  console.log("You are too young to vote");
}

else if Ladder

When we need to check multiple conditions, we use else if.

Syntax

if (condition1) {
  // code
} else if (condition2) {
  // code
} else {
  // default code
}
let marks = 75;

if (marks >= 90) {
  console.log("Grade A");
} else if (marks >= 70) {
  console.log("Grade B");
} else if (marks >= 50) {
  console.log("Grade C");
} else {
  console.log("Fail");
}

switch Statement

The switch statement is used when we want to compare one value against multiple possible options.

Syntax

switch (expression) {
  case value1:
    // code
    break;

  case value2:
    // code
    break;

  default:
    // code
}
let day = 3;

switch (day) {
  case 1:
    console.log("Monday");
    break;

  case 2:
    console.log("Tuesday");
    break;

  case 3:
    console.log("Wednesday");
    break;

  default:
    console.log("Invalid day");
}

break Statement

The break statement stops the switch execution.

Without break, JavaScript continues executing the next cases.

Example without break:

let day = 1;

switch (day) {
  case 1:
    console.log("Monday");

  case 2:
    console.log("Tuesday");
}

// without break
// o/p will be

// Monday
// Tuesday

When to Use switch vs if-else

Conclusion

Control flow is an essential part of programming because it allows our programs to make decisions based on conditions.