Skip to main content

Command Palette

Search for a command to run...

Control Flow in JavaScript : If, Else, and Switch

Updated
•6 min read•View as Markdown
Control Flow in JavaScript : If, Else, and Switch

Control Flow :

What is control flow in real life ?

Let's understand with the Student Life example :

When Student passed out class 10th , Student have some stream to select for class 11th , here some students decide their stream according to their future , some students decide their stream according to their friends, and some student are forced by parents to taking the stream.

After taking Stream, When Student passed out class 12th from their stream , they have their options to take any course, degree and college according to their stream.

After taking course and college, When Student passed out college, they have to decide their career , which career they want to pursue.

Here From 10th to 12th to College to Career , this is in control flow and it is control by student or by their friend or by their parents .

What is the mean of control flow in programming?

In the programming , we have if - else and Switch to control our program flow. Using this control statement we control the flow of programming.

Lets understand if, if-else and else if with example :

IF

If is the controlling statement, where our block of code inside the if execute when if condition is true.

Let's take an example :

// Here we take an example of Jethalal and Bhide Income from TMKOC Indian comedy show : 

let jethalal_income = 100_000_000;
let bhide_income = 100000;

if(jethalal_income>bhide_income){
    console.log("Bhide Gareeb hai , or Matlab Jo gareeb ho na aadmi vo apni aadat se gareeb ho ") ;
} 

if(bhide_income>jethalal_income){
    console.log("Impossible") ;
}

In the code, you see that our first if condition is satisified that jethalal income is more than bhide , then our code block inside the if is execute . and in the second condition which is always false in real life and code , then the block of code inside the second if can not execute.

Above code you can see that we have to write two if for two opposite condition , opposite condition mean if the first condition is true then our second condition is always false. We can write the opposite condition using IF-ELSE .

IF-ELSE

IF-Else is the controlling statement , where we check the condition in the if , if it is true then the code blocks inside the if execute or if it is false then our else code block execute .
We can not use else without if.

Lets Take again same example :

// Here we take an example of Jethalal and Bhide Income from TMKOC Indian comedy show : 

let jethalal_income = 100_000_000;
let bhide_income = 100000;

if(jethalal_income>bhide_income){
    console.log("Bhide Gareeb hai , or Matlab Jo gareeb ho na aadmi vo apni aadat se gareeb ho ") ;
}else{
    console.log("Impossible");
}

In the code you can see that , if jethalal_income>bhide_income is true then our console.log() inside if work and if it is false then our else console.log() exexute.

Else-IF

Else-IF is the condition which is used in the between of if and else we can chain our if-else using else-if. we can not use else-if without if it throw an error.

Lets take an example of Else-IF with IF and Else

// Take an example of my expectations after 12th 

let JEE_Clear = false ;
let CUET_clear = false ;
let 12th_pass = true ;

if(JEE_Clear){
    console.log("IIT/NIT College mil jayega") ;
} else if(CUET_clear) {
    console.log("Koi achha college mil jayega") ;
} else if(12th_pass){
    console.log("Koi sa bhi college mil jayega") ;
} else{
    console.log("yadav hai : Hum Bhains Chara ke duh ke pi lenge, Bech lenge ") ;
}

Nested If Else :

When we write if -else condition inside if-else it called Nested IF-ELSE , it needed when we have to check our condition inside the condition .

Lets understand with some real examples :

// Lets take an Example of Imagination of B.Tech CSE guy

let imagination = true ;
let firstyr_DSA = true;
let secondyr_Dev = true ;
let thirdyr_Internship = true ;
let fourthyr_50LPA = true ;
let work = false ;

if(imagination){
    if(firstyr_DSA){
        console.log("First year mein DSA Ho jayega");
        if(secondyr_Dev){
            console.log("Second year mein Development ho jayega");
            if(thirdyr_Internship){
                console.log("Third year mein Internship lag jayegi");
                if(fourthyr_50LPA){
                    console.log("fourth year mein college ka sabse bada package le lunga");
                }
            }
        }
    }
}else if(work){
    if(firstyr_DSA){
        console.log("First year mein DSA ho gaya");
        if(secondyr_Dev){
            console.log("Second year mein Development ho gaya");
            if(thirdyr_Internship){
                console.log("Third year mein Internship lag gayi");
                if(fourthyr_50LPA){
                    console.log("fourth year mein college ka sabse bada package le liya");
                }
            }
        }
    }
}else{
    console.log("Hum Bhains Chara ke duh ke pi lenge, Bech lenge ") ;
}

Switch :

A switch statement is used for multi-branch decisions based on the value of a single expression, providing a cleaner alternative to a long if-else-if ladder, especially when you have many possible outcomes. The break keyword is essential for controlling the flow within the switch block.

Lets understand with an example :

// Take an example of Lift

switch (floorRequest) {
    case 1:
        display("Going to Floor 1");
        // Code to move the lift to floor 1
        break;
    case 2:
        display("Going to Floor 2");
        // Code to move the lift to floor 2
        break;
    case 3:
        display("Going to Floor 3");
        // Code to move the lift to floor 3
        break;
    default:
        display("Invalid Floor Selected");
        // Code to handle an invalid input
}

The break keyword's primary role in a switch statement is to terminate the switch block entirely once a matching case has been executed. Without it, the program will continue to execute the code blocks of subsequent cases, even if those cases don't match the original expression's value. This behavior is called "fall-through".

  • With break: If the floorRequest is 2, the code for case 2 runs, and then break stops the switch execution.

  • Without break: If the floorRequest is 2 and there were no break statements, the code for case 2, case 3, and the default would all run sequentially until the end of the switch block.

Use a switch statement when:

  • You are testing a single variable against a large number of fixed, constant values (e.g., specific integer values, characters, or strings, depending on the language).

  • The code with multiple conditions needs to be cleaner and more readable than a long if-else-if chain.

  • You need slightly faster execution in some scenarios, as compilers can optimize switch statements more efficiently (e.g., using jump tables) when there are many cases.

Use an if-else statement when:

  • You need to evaluate complex conditions involving logical operators (e.g., &&, ||) or a range of values (e.g., score >= 90 and score <= 100).

  • You are checking conditions based on boolean expressions or multiple variables.

  • There are only one or two conditions to check, as the if-else structure is simpler for such cases.

- Written By : Vivek yadav