Skip to main content

Command Palette

Search for a command to run...

Control Flow in JavaScript: If, Else, and Switch Explained

Updated
9 min read
Control Flow in JavaScript: If, Else, and Switch Explained

Introduction:

Conditional statements in JavaScript allow the program to make decisions and execute different blocks of code based on whether a condition is true or false.

Definition : In any programming language, the code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. In this article, we'll explore how so-called conditional statements work in JavaScript.

Control flow in programming:

In programming, control flow refers to the order in which the instructions or statements of a program are executed. By default, code runs sequentially from top to bottom, but control flow statements allow developers to alter this path dynamically based on conditions, decisions, and events.

Key Control Flow Constructs :

Control flow dictates program logic through three main types of structures:

  • Conditional Statements (Selection): Direct code execution based on boolean conditions (if, else, switch).

  • Loops (Iteration): Repeatedly execute code until a condition is met (for, while, do-while).

  • Jump Statements: Immediately transfer execution, such as break, continue, return, or exception handling via throw .

In JavaScript, the main conditional structures are:

  • if and else

  • if...else if...else (also called if-else ladder)

  • switch statement

Let’s explore each of them step by step.

The if Statement :

The if statement is used to run a block of code only if a condition is true.

Syntax:

if(condition){
    // code to run if condition is true
}

For example :

let age = 20
if (age > 18) {
    console.log("you are eligibel for vote")
}

Output:

you are eligible for vote

=== Code Execution Successful ===

Explanation: Here, the condition age >= 18 is true, so the message "You are eligible for vote." will be printed. If it were false, the code inside the if block would simply be skipped.

The if...else Statement :

Sometimes you want to run one block of code if the condition is true, and another block if it’s false. That’s where else comes in.

Syntax:

if (condition) {
  // runs if condition is true
} else {
  // runs if condition is false
}

For example :

let age = 12
if (age > 18) {
    console.log("you are eligibel for vote");
}else{
    console.log("slow down bacha you have time to vote");
}

Output:

slow down bacha you have time to vote

=== Code Execution Successful ===

Since the age < 18 , the else part executed.

The else if ladder :

When you have multiple conditions to check, using just if and else becomes messy. That’s where the if-else ladder (also called a chain) helps you can check several conditions in sequence.

Syntax:

if (condition1) {
  // code if condition1 is true
} else if (condition2) {
  // code if condition1 is false and condition2 is true
} else if (condition3) {
  // code if the above are false but this is true
} else {
  // code if none of the conditions are true
}

For example :

let marks = 15

if (marks >= 90) {
    console.log("Grade O");
} else if (marks >= 80) {
    console.log("Grade A");
} else if (marks >= 70) {
    console.log("Grade B+");
} else if (marks >= 60) {
    console.log("Grade B");
} else if (marks >= 50) {
    console.log("Grade C+");
} else if (marks >= 40) {
    console.log("Grade C");
} else if (marks >= 33) {
    console.log("Grade P");
} else {
    console.log("Grade F");
}

Output:

Grade F

=== Code Execution Successful ===

The switch Statement

If you’re comparing a single value against multiple possible options, the switch statement is a cleaner alternative to multiple if...else if conditions.

Syntax:

switch (expression) {
  case value1:
    // code if expression === value1
    break;
  case value2:
    // code if expression === value2
    break;
  default:
    // code if none of the above cases match
}

For example :

let day = "Sunday"

switch (day){
    case "Monday":
      console.log("It's just start of week bro");
      break;
    case "Tuesday":
      console.log("Keep doing your work");
      break;
    case "Wednesday":
      console.log("It's just half of week bro");
      break;
    case "Thursday":
      console.log("Keep going");
      break;
    case "Friday":
      console.log("Finally, it's coming");
      break;
    case "Saturday":
      console.log("Just one more day");
      break;
    default:
      console.log("Bro just died of waiting sunday.");
      break;
}

Output:

Bro just died of waiting sunday.

=== Code Execution Successful ===

Explanation: Here, JavaScript checks which case matches the value of day. When it does not finds "Sunday", it runs the default and give the value in the default.

When to use switch vs if-else :

The decision between using switch and if-else depends on the specific logic, aiming for the most readable and maintainable code. Generally, switch is preferred for multiple fixed values of a single expression, while if-else is used for complex conditions, ranges, or multiple variables. Use if-else when: - You need complex conditions: if-else statements can evaluate a wide variety of conditions using logical and relational operators (e.g., if (x > 10 && x < 50)). - You are testing ranges of values: You need to check if a value falls within a specific range (e.g., a grading system based on score ranges). - You are working with different data types: if-else can evaluate boolean, integer, floating-point, character, and string types (though some modern languages allow switch with strings and enums). - You need flexibility in conditions: Each condition is independent and can involve different variables or complex logic. Use switch when: - You have multiple choices for a single, fixed value: The primary use case for switch is when comparing one expression against a list of specific, constant values (e.g., status codes, menu options, days of the week). - Readability is a priority for many options: A switch statement can be much cleaner and easier to read than a long chain of if-else-if statements. - Performance might be a concern with many cases: Compilers can often optimize switch statements into efficient "jump tables," allowing direct access to the matching code block, which can be faster than the sequential evaluation of a long if-else-if chain. - You want to utilize fall-through behavior (with caution): In many languages, omitting the break statement allows execution to "fall through" to the next case, which can be useful for handling multiple related cases with the same logic. Ultimately, the best choice is the one that makes the code's logic most immediately clear and maintainable to you and other developers.

Write a program that checks:

    • If a number is positive, negative, or zero :
let number = 0;

if (number === 0) {
    console.log("Number is Zero");
} else if (number > 0) {
    console.log("Number is positive");
} else {
    console.log("Number is negative");
}

Output:

Number is Zero

=== Code Execution Successful ===

Write a program that prints the day of the week using switch :

let day = "Monday";

switch(day){
    case "Monday":
      console.log("Monday");
    case "Tuesday":
      console.log("Tuesday");
    case "Wednesday":
      console.log("Wednesday");
    case "Thursday":
      console.log("Thursday");
    case "Friday":
      console.log("Friday");
    case "Saturday":
      console.log("Saturday");
    case "Sunday":
      console.log("Sunday");
      break;
}

Output:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

=== Code Execution Successful ===

which control structure is mostly used and why :

The most used control structure in JavaScript is:

if...else statement

Because it is:

  • More flexible

  • It can handle complex conditions

  • It can use logical operators (&&, ||, !)

  • It works with ranges, comparisons, and dynamic logic

For example :

let marks = 15

if (marks >= 90) {
    console.log("Grade O");
} else if (marks >= 80) {
    console.log("Grade A");
} else if (marks >= 70) {
    console.log("Grade B+");
} else if (marks >= 60) {
    console.log("Grade B");
} else if (marks >= 50) {
    console.log("Grade C+");
} else if (marks >= 40) {
    console.log("Grade C");
} else if (marks >= 33) {
    console.log("Grade P");
} else {
    console.log("Grade F");
}

Output:

Grade F

=== Code Execution Successful ===

Some of you think that this example is of else if , but let me clear it :

This whole structure of if...else if...else is still called an if...else control structure.

This has 3 parts:

if

Checks the first condition

if (marks >= 90)

If true - runs this block and stops.

else if

Checks another condition if previous one was false

else if (marks >= 80)

You can have multiple else if.

else

Runs if none of the above conditions are true

else

This is the final fallback.

Why it's still called if...else structure :

Because:

  • else if is just an extension of if...else

  • The full name is:

if...else if...else control structure

But commonly people say:

if...else structure

Conclusion :

JavaScript control statements are used to control the flow of program execution based on conditions and logic. They help the program make decisions, repeat tasks, and execute specific blocks of code only when required. The most commonly used control statements include if...else, switch, and loops like for and while.

Using control statements makes programs smarter and more dynamic, allowing them to respond differently to different inputs. For example, they can be used to assign grades, validate user input, or manage application behavior.

In short, control statements are the backbone of decision-making in JavaScript. Without them, programs would run line-by-line without any logic or flexibility. Mastering control statements is essential for writing efficient, interactive, and real-world JavaScript applications.