Skip to main content

Command Palette

Search for a command to run...

Control Flow: if, if-else & switch explained

Updated
5 min read
Control Flow: if, if-else & switch explained

Control Flow

  • How do you prepare your coffee? Can you guide me through each step you partake in.

  • Well, you might ask "Hey buddy, what do you mean by coffee? Is it americano? Cappuccino?" And you would be right based on my input the steps might change.

  • This is exactly what happens in a program too.

  • Control Flow is the order in which the code written by us developers, execute instructions line-by-line.

  • It uses conditional statements (if/else), loops (for/while), and functions to make decisions, repeat actions, or branch to different code paths based on conditions.

Conditionals

  • Imagine you and your friends finally made a plan and came through, and finally in 4 years you are going on a road trip. But, how do you decide which route to take?

  • It depends. Am I right?

  • It depends on where you're going, do you value journey or reaching in paramount, are you all travelling by train, bus, or car or perhaps a ship? So, short answer it depends.

  • Our real world is a mesh of decisions being taken by all those who inhabit it. Similarly, in our programming world, we need to be able to direct them based on conditions and criteria.

  • Hence, handling the direction the code will take is one of the most fundamental component of any program, and it is known as Conditionals.

  • Conditionals enable us to execute different code-blocks depending on conditions. The code used for this is:

if(condition){
//code if condition is met
}
else{
//code if condition is not met
}

"if" statement

  • The most fundamental unit of decision making(conditional) in programming.

  • The syntax and understanding of if is quite instinctive. You provide the condition in the () and if that condition is met, the code block inside the {} is executed.

  • It simply follows if this then execute {function}

const age = 21;
if(age >=18){
    console.log("Eligible for driving license");
};
//Output: Eligible for driving license 

"if-else" statement

  • if-else is a level above if statement.

  • In the case of if-else we not only provide code block that is executed when a condition is met, but also what code to execute if the condition is not met.

const typeFood = "mild";
if(typeFood == "spicy"){
    console.log("Ordered");
}else{
    console.log("Exit");
};

//Output: Exit
  • Here since the condition is not met, the else block is executed.

"else-if" ladder

  • The ladder of if(cond1){...}else-if(cond2){...}else{...}, is a a control structure used to execute different blocks of code based on multiple, sequential conditions. Conditions are checked from the top down, and the first one that evaluates to true has its corresponding code block executed, after which the rest of the ladder is skipped.
const num = 0;
if(num > 0){
    console.log("Positive number");
}
else if(num == 0){
    console.log("Zero");
}
else{
    console.log("Negative number");
}

//Output: Zero

Code Works

  1. The program starts by storing the variable.

  2. Then we check the if condition first, and we proceed with the corresponding code block if condition is met, and with that the ladder is exited.

  3. Then we follow by verifying the next else if(condition) and then we follow execution or not depending on the condition.

  4. If none of the conditions are met else block is executed.

Switch

  • The Expression: The switch statement evaluates an expression once and compares its result with the values of each case.

  • The switch case has some limitations in comparison to

let fruit = "Apple";

switch (fruit) {
  case "Banana":
    console.log("Bananas are $1.00");
    break;
  case "Apple":
    console.log("Apples are $1.50");
    break;
  default:
    console.log("Sorry, we are out of " + fruit);
}

'break'

  • A very important part of the switch structure is the break keyword.

  • Execution Termination: The break keyword tells the JavaScript engine to stop executing code inside the switch block and "jump out" to the next line of code after the closing brace }.

  • Preventing "Fall-through": Without a break, the engine continues into the next case regardless of whether that case matches the expression. This is known as fall-through.

When to use what(switch vs if-else)

When to Use if-else

  • Complex Logic & Ranges: If you need to check ranges (e.g., age > 18 && age < 30) or multiple different variables in one go, if-else is the only way.

  • Boolean Comparisons: If you are simply checking if something is true or false, a switch is overkill.

  • Non-Equality Checks: If you are using operators like > (greater than), < (less than), or !== (not equal), if-else is built for this.

When to use switch

  • Fixed Values: Use switch when you are checking a single variable against specific, discrete values (like "Red", "Green", "Blue").

  • Multiple Outcomes for One Variable: When an if-else chain starts looking like a "ladder" (more than 3-4 else if blocks), a switch is much cleaner to read.

  • Shared Logic (Fall-through): If multiple different inputs should trigger the exact same code, switch allows you to group them elegantly without repeating code.

Conclusion

  • Hopefully you learned something. I hope you experience a really good weekend.

  • I'd like to thank the chaicode team. Yeah. No, yeah. That's it.

Control Flow: if, if-else & switch explained