DEV Community

Cover image for Control Flow in JavaScript: If, Else, and Switch Explained
Soubhagya Dash
Soubhagya Dash

Posted on

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

So far, we’ve learned how JavaScript stores and works with data. Now let’s see how it makes decisions.

In real life we always end up making some decisions like:-

You’ve finally found the perfect pair of shoes. 👟
You check the price… ₹2,000.
Then you check your wallet… ₹2,500.
If your budget is enough -> Congratulations, those shoes are coming home with you! 🛍️
Else -> Time to close the tab and save some money. 😭💸

In JavaScript, code doesn’t always execute blindly from top to bottom. It can make decisions about what to execute, what to skip, and what to repeat. That’s where Control Flow comes into the picture - it determines the path your code follows while executing.

const isBudgetFriendly = true

if(isBudgetFriendly) {
console.log("Home coming new shoes")
} else {
console.log("Save money! Try next time")
}
Enter fullscreen mode Exit fullscreen mode

Now, let’s explore each control flow statement one by one.

Conditional Statement:-

We've previously read some conditional operators. So we know that using them, we can make some conditions. As a result, it comes with a boolean value. So, using these conditions, we can write conditional statements.

Basically, Conditional statements are a type of control flow statement that allow JavaScript to make decisions based on whether a given condition is true or false.

These are some conditional statements in javascript we're going to cover:-

  • if statement
  • if...else statement
  • else if ladder
  • switch statement

let's move to the first one...

1. if statement

This statement contains only one condition and executes only when that condition is true. It is the simplest form of a conditional statement in JavaScript.

this is the syntax of an if statement.

if (condition) {
 // what to do
}
Enter fullscreen mode Exit fullscreen mode

In real life, we often do something only when a particular condition is satisfied. An if statement works in exactly the same way; if the condition is true, the code inside it gets executed.

Let's take a look for a real example:-

Let's assume the results are finally out… 😰 If your marks are 40 or above -> You’re officially a survivor. 🎉

let marks = 72;

if (marks >= 40) {
    console.log("You passed! 🎉");          // You passed! 🎉
}
Enter fullscreen mode Exit fullscreen mode

how code runs in step by step:-

  1. Firstly javascript will check if the condition is true or not.
  2. If the condition is true then it'll execute the code inside it's block scope.
  3. If the condition is false javaScript simply skips that block and moves to the next line of code.

2. if else statement

This statement works on the basis of two possible conditions. If the condition is true, it does one thing; otherwise, it does something else. We can handle two possible outcomes at a time using the if...else statement.

this is the syntax of an if else statement.

if (condition) {
 // Do something
} else {
 // Do another thing
}
Enter fullscreen mode Exit fullscreen mode

In real life, we often make decisions based on whether a particular condition is true or false. An if...else statement works in the same way; if the condition is true, the code inside the if block gets executed, otherwise, the code inside the else block gets executed.

Let's take a look for a real example:-

The moment of truth has finally arrived… 😰
You open your result, your heart starts racing, and then you look at the marks.
If your marks are 40 or above → Congratulations! You made it! 🎉
Else → Looks like it’s time for another battle. 📚😭

let marks = 65;

if (marks >= 40) {
    console.log("You passed! 🎉");
} else {
    console.log("Better luck next time! 📚");
}
Enter fullscreen mode Exit fullscreen mode

how code runs in step by step:-

  1. First, JavaScript checks whether the condition is true or not.
  2. If the condition is true, it executes the code inside the if block and ignores the else block.
  3. If the condition is false, JavaScript moves to the else block and executes the code inside it.

3. else if statement

The else if condition comes into play when you have multiple conditions. If the very first condition is true, JavaScript executes its code. Otherwise, JavaScript moves to the second condition. If the second condition is also false, it moves to the third condition, and this continues until it finds a true condition or reaches the last condition.

this is the syntax of an else if statement.

if (condition) {
 // Do something
} else if (condition2) {
 // Do another thing
} else {
 // Do something else
}
Enter fullscreen mode Exit fullscreen mode

In real life, we often face situations where there can be multiple possible outcomes. An else if statement helps us handle these situations by checking different conditions one by one.

Let's take a real-life example:

The results are finally out… 😰 You open your marks and now your fate is decided!
If 90+ --> You’re a topper! 🏆
Else if 75+ --> Solid B! 😎
Else if 60+ --> You made it! 🫡
Else --> Time for the comeback! 📚😭

let marks = 82;

if (marks >= 90) {
    console.log("Grade A 🏆");
} else if (marks >= 75) {
    console.log("Grade B 🔥");            // Grade B 🔥
} else if (marks >= 60) {
    console.log("Grade C 👍");
} else {
    console.log("Time to hit the books again! 📚😭");
}
Enter fullscreen mode Exit fullscreen mode

How the code runs step by step:

  1. If the first condition is true, the code inside the if block executes, and the remaining conditions are ignored. Otherwise, JavaScript moves to the next condition.
  2. If the second condition (else if) is true, it executes the code inside its block and ignores the remaining conditions.
  3. This process continues until a condition is satisfied.
  4. If none of the else if conditions is true, JavaScript moves to the final else statement and executes the code inside the else block.

4. switch statement

A switch statement is used when you want to check one value against multiple possible values.

the syntax of the switch statement is:-

switch(expression) {

  case value1:
    // code
    break;

  case value2:
    // code
    break;

  default:
    // code if none of the cases match

}

Enter fullscreen mode Exit fullscreen mode

In real life, we often come across situations where there are many possible choices. A switch statement helps us handle these situations by checking a value and choosing the matching option.

Imagine you are driving and you reach a traffic signal.
If the signal is red, you stop.
If the signal is yellow, you wait and get ready .
If the signal is green, you go.
The action depends on the current color of the signal.

A switch statement works in a similar way. It checks the value of the signal and performs the action associated with that value.

let signal = "green" ;

switch(signal) {

  case "red":
    console.log("Stop");
    break;

  case "yellow":
    console.log("Wait and get ready");
    break;

  case "green":
    console.log("Gooooo");
    break;

  default:
    console.log("Not a valid signal");

Enter fullscreen mode Exit fullscreen mode

break works when the case matches to the value and it tells javascript to stop right now.

default executes only when none of the test cases matches.

How the code runs step by step:-

  1. First, it evaluates the expression written inside the switch.
  2. It then checks the value against each case one by one.
  3. When it finds a case that matches the value, the code inside that case is executed.
  4. If the case contains a break statement, JavaScript stops the execution of the switch and moves to the code after it.
  5. If none of the cases match, JavaScript executes the default block, if it is present.

Difference between if...else if and switch

Both if...else if and switch statements are conditional control statements used to make decisions in a program based on different possibilities.

But the main difference is how they check those possibilities.

if...else if is used when we need to check different conditions that contain comparisons such as greater than, less than, equal to, or logical operations.

switch is used when we have one value and want to compare it with multiple specific values, called cases.

Basically Use switch when you have one value and want to compare it with many possible values.

_______________________________ X _______________________________

That's it for today! We covered all the major control flow statements in JavaScript and understood how they work with different conditions.
See you in the next one! ✌️

Top comments (0)