Page Content

Tutorials

How to Use JavaScript Switch Statement Over If Else If?

JavaScript Switch Statement

Logic statements in JavaScript let you construct distinct code paths based on an expression’s result. This implies that your code need not be static and execute the same function each time. For this conditional execution, branching statements such as switch, if, and if else are utilised.

Depending on the different values of a single expression, you can choose which of several code blocks to execute using the switch statement, a conditional statement. When analysing more than four or five values, it offers a more descriptive and frequently cleaner option than a lengthy sequence of i else if else expressions. Switch is meant to convey dispatching on a value in a more straightforward manner, even though a sequence of if else if could appear more appealing in some situations.

The basic syntax for a switch statement is as follows:

switch (expression) {
case value1:
// code to be executed if expression === value1
break; // Important!
case value2:
// code to be executed if expression === value2
break; // Important!
// … potentially more cases
default:
// code to be executed if expression doesn’t match any case
break; // Optional if last, but good practice
}

An expression enclosed in parenthesis and a block of code enclosed in curly braces after the switch keyword. Case labels, which are enclosed in curly braces, are composed of the case keyword, an expression, and a colon.

The switch statement functions as follows:

  1. The expression given after the switch keyword is evaluated.
  2. A case label whose expression evaluates to the same value as the switch expression is then sought after.
  3. Strict type checking (===) is used to check for equality between the values of the switch expression and the case expression. This verifies the data type as well as the value.
  4. The software begins running the statements right after that case label if a matched case is discovered.

JavaScript Switch Statement Over If Else If

A flexible method for testing a number of conditions is the if…else if structure. An initial if statement that evaluates an expression comes first. The code block linked to the if statement is run if the expression is truthy. The optional else block is run if the initial if condition is false. After the first if block, you can add else if blocks to link other conditions. JavaScript halts testing as soon as a condition evaluates to true, and the code is run from top to bottom. The only code block that is run is the one linked to the first true condition.

Here is an example of an if…else if chain, demonstrating different messages based on the time of day:

let time = new Date().getHours();
let message;

if (time < 12) {
message = “Good Morning!”;
} else if (time < 17) {
message = “Good Afternoon!”;
} else if (time < 20) {
message = “Good Evening!”;
} else {
message = “Good Night!”;
}

console.log(message);

This structure skips the other if conditions and assigns “Good Morning!” if the time is less than twelve. “Good Afternoon!” is allocated if the time is less than 17 but not less than 12, and so on. If none of the aforementioned requirements are satisfied, the last else serves as a backup.

The switch statement provides a more streamlined option for comparing a single expression to several potential fixed values, even if the if…else if statement can be used to evaluate any Boolean condition or sophisticated logic. When assessing values greater than four or five, this is especially helpful.

The switch keyword appears first in the syntax of a switch statement, followed by an expression enclosed in parenthesis. You specify distinct case blocks inside curly braces. A colon and a possible value follow each case. JavaScript uses rigorous equality (===) to compare the value of the switch expression with each case value. Should a match be discovered, the code inside that case block begins to run.

The break keyword in switch statements is essential. In the absence of a break statement, regardless of whether the subsequent case value matches, execution will “fall through” and move on to the following case block. Although fall-through can occasionally be used on purpose, it is frequently a cause of issues, thus unless you specifically intend to fall through and have commented appropriately, it is best practice to include break at the end of each instance. If none of the case values fit the expression, the default case, which is optional, runs.

let activity = “Lunch”; // Or “Get up”, “Breakfast”, “Drive to work”, etc.
let timeMessage;

switch(activity) {
case “Get up”:
timeMessage = “It is 6:30AM”;
break; // Stops execution after this case
case “Breakfast”:
timeMessage = “It is 7:00AM”;
break;
case “Drive to work”:
timeMessage = “It is 8:00AM”;
break;
case “Lunch”:
timeMessage = “It is 12:00PM”;
break;
case “Drive home”:
timeMessage = “It is 5:00PM”;
break;
case “Dinner”:
timeMessage = “It is 6:30PM”;
break;
default: // Executes if no case matches
timeMessage = “I cannot determine the current time.”;
break;
}

console.log(timeMessage);

If several cases should run in the same code block, you can combine them by listing them one after the other before the code and the break statement.

In conclusion, complicated logic and a variety of Boolean conditions can be evaluated with the flexibility of if…else if chains. When comparing a single expression to a predetermined set of discrete values, switch statements are frequently chosen over lengthy if…else if chains because they are easier to read and occasionally more efficient. In the end, the decision is based on the particular logic needed and, to some degree, personal preferences for coding style.

Index