Skip to main content

Command Palette

Search for a command to run...

JavaScript Control Flow Explained: If, Else, Else If & Switch with Examples

A beginner guide towards conditionals.

Updated
7 min read
JavaScript Control Flow Explained: If, Else, Else If & Switch with Examples
R

I write code,fix bug, and solve problem.

Imagine you are driving your car and you reach a traffic signal. At that point, you must follow the rules set by the government for traffic signals. Suppose you arrive at the signal and it suddenly turns red. What would you do? Naturally, you would stop your car and wait until the signal turns green.But what actually made you decide to stop when the light turned red and move when it turns green? The condition of the signal determines your action. If the signal is red, you stop. If the signal is green, you go.

This is a simple real-life example that helps us understand conditionals in JavaScript. Just like traffic signals control your driving actions based on conditions, JavaScript uses conditional statements (like if, else, and switch) to decide what action a program should take based on different conditions. Below image is showing its correlation with that of conditionals in JavaScript


" Conditionals allows a program to choose what to do next based on condition meet"

In Programming, there are different way to utilize conditional we will discuss each with simplified example :

  1. The if Statement:
    It is most basic conditional in JavaScript which only got triggered for true value , it does not handle false condition :
const age=25;

if(age>=18){
console.log("Person Can cast vote")
    }
console.log("I will run every time")

// Here in above code age is 25 which is greater than 18 so statement under that if block will be executed and you will see output as "Person Can cast vote" and next line will be "I will run every time"

const newAge=17;

if(newAge>=18){
console.log("Person Can cast vote")
    }
console.log("I will run every time")

// Here in second example newAge is 17 which is less than that of 18 it means condition newAge>=18 will result false and it result in skip of statement written under IF block and you will only see "I will run every time"
  1. The IF-ELSE Statement:
    This is also basic conditional checker in JavaScript which can handle both true and false conditions , true condition related work perform under if block and false condition related work perform under else block. We can also view its Flow diagram below to get better understanding.

    Some Examples to clarify it:

const age=25
    
if(age>=18){
    console.log("You can cast vote.")
 }else{
console.log("You cannot cast vote.")
}

// Here in above example both true and false conditions got handled :
// here age=25 which means condition will be true as it is greater than 18 as per condition in under IF so it went to if block and we see output as "You can cast vote" if we try above age=12 , condition will be false and else block will get executed and we will see output as You cannot cast vote.
    
  1. The else-if Statement:
    else-if is also known as ladder if-else ,using if-else we can handle one condition at a time but think of situation when we have to check multiple conditions.Using if-else we can do that but we need to use multiple if which is not a good approach so for managing multiple condition checks else-if introduced . Here first condition check with If and further condition checked using else if and ends with else.lets discuss one example to understand this clearly.
// we have to check a number whether it is positive, negative or zero 

const num = -20;

if (num > 0) {
  console.log("number is positive.");
} else if (num < 0) {
  console.log("number is negative.");
} else {
  console.log("number is zero");
}

// Here in above example we have taken num = -20
// first it goes to fist condition validation at if(num>0) result will be if(false) means it will skip block under if and jump to second else if(num<0) here condition is true because number -20 is less than 0 so result would be else if(true) and statement under this block got executed and we will see output as "number is negative"
  1. The switch statement:
    Switch consist of mainly three keywords switch , case , default . It is generally used when we need to compare one variable against multiple values , we can understand it as we have fixed values and one by one we compare provided input with all possible values if it matched perform operation based on provided logic.
    If by any change our input value does not meet with any compared value then a default case statement will get executed and logic under that got triggered. Below is branching diagram of switch case statement:

    There is one gotcha in switch-case , if we forgot apply break and first case got matched then all the further case logic will get executed lets understand it with one example.

let fruit = "apple";

switch(fruit){

   case "apple":
      console.log("This is an apple");

   case "banana":
      console.log("This is a banana");

   case "orange":
      console.log("This is an orange");
}

/*
 Here in above example we have not used break;

Here first case is true so that it should display only "This is an apple" but output will not be like this instead we will get :

This is an apple
This is a banana
This is an orange

This is not actual output which we are expecting so we use break after statement in each case like below :


*/

switch(fruit){

   case "apple":
      console.log("This is an apple");
        break;

   case "banana":
      console.log("This is a banana");
        break;

   case "orange":
      console.log("This is an orange");
        break;
}

Lets take one more example to clearly Understand working of switch case:

let day = 3;

switch(day){

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

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

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

   case 4:
      console.log("Thursday");
      break;

   case 5:
      console.log("Friday");
      break;

   case 6:
      console.log("Saturday");
      break;

   case 7:
      console.log("Sunday");
      break;

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

/**

Here  we have provided day = 3 so the case matches it is case 3: so it will display Wednesday as output and that's it. it will not display further values like Thursday,Friday,Saturday,Sunday because we have used break to forcefully stop further checking.
*/

In the above example for printing the day of the week, we used a switch statement. The same problem could also be solved using an else-if , but switch is more suitable in this case.The reason is that we are simply matching the value of a single variable (day) with several fixed values (1–7). No additional logical conditions or comparisons are required.

When the task is to compare one variable against multiple constant values, a switch statement provides a cleaner and more readable structure. Each possible value is handled using a separate case, which makes the code easy to understand.

Although the problem can also be solved using if–else conditions, the code becomes longer and harder to maintain, especially when the number of comparisons increases.

Therefore, in situations where we only need to match a variable with predefined fixed values, using a switch statement is generally a better and more organized approach than an else-if .


Conclusion:

Control flow is a fundamental concept in JavaScript that allows programs to make decisions and execute different blocks of code based on specific conditions. Statements such as if, if-else, else if, and switch help developers control how a program behaves in different situations.

The if statement is useful when we want to execute code only when a condition is true. The if-else statement allows us to choose between two possible outcomes, while the else if helps evaluate multiple conditions sequentially. When we need to compare a single variable with several fixed values, the switch statement provides a cleaner and more organized structure.

Understanding when to use if-else and when to use switch helps developers write code that is easier to read, maintain, and scale. These control flow statements form the backbone of decision-making in JavaScript and are widely used in real-world applications such as user authentication, form validation, and application logic.

We hope this blog helped you understand control flow in JavaScript, including if, else, else-if, and switch statements with practical examples. If you found this article helpful or noticed anything that could be improved, feel free to share your feedback. Continuous learning and improvement are key to becoming a better developer.