Mastering the JavaScript Switch Statement

Are you wondering what the JavaScript switch statement is? If so, keep on reading!

In this article, we will discuss in detail the switch statement in JavaScript. Are you excited about that?

So, without further ado, let’s get started on learning new concepts and eventually mastering the JavaScript switch statement.

What is switch statement in JavaScript?

The switch statement in JavaScript is a type of conditional statement that is used to perform different actions based on different conditions.

It’s like a series of if statements, but more efficient when dealing with multiple conditions.

Syntax

Here’s the syntax of a JavaScript switch statement:

switch(expression) {
    case value a:
        // code block
        break;
    case value b:
        // code block
        break;
    default:
        // code block
}

Parameter

expression

This is the condition that is evaluated once. The result of the expression is compared with the values of each case.

case value

If the expression matches the value, the associated block of code is executed.

default

If no match is found among the cases, code specified in the section labeled by default is executed.

Here’s an example code:

let time;
let subject = new Date().getHours(); // This will give you the current hour (0-23)

switch(subject) {
  case 1:
    time = "English";
    break;
  case 2:
    time = "Math";
    break;
  case 3:
    time = "Science";
    break;
  case 4:
    time = "Software Engineering";
    break;
  case 5:
    time = "Web Development";
    break;
  case 6:
    time = "Programming";
    break;
  default:
    time = "Subject not found";
}

console.log(time);

Output:

Programming

How JavaScript switch statement works?

Here’s how it works:

The switch statement in JavaScript is a useful tool for controlling the flow of your code based on specific conditions.

It works by evaluating an expression once and then comparing the result with the values specified in each case within the switch block.

When a match is detected, the code block linked to that specific case is carried out.

This allows you to perform different actions for different conditions in a very efficient way.

However, if no match is found among the case values, the code block under the default case is executed. This serves as a catch-all for any values not explicitly handled by your case statements.

📌 Please keep in mind that each case should end with a break statement to prevent “falling through” to the next case.

If you forget to include a break, JavaScript will continue executing the next case’s code block regardless of whether it matches or not.

This can lead to unexpected behavior, so always remember to include those break statements!

What is the break keyword in switch statement?

In a JavaScript switch statement, the break keyword is used to exit the switch block.

This means that once the JavaScript engine finds a case where the condition is met, it executes the associated code block and then breaks out of the switch block.

Here’s an example:

let subject = 'Programming';

switch(subject) {
case 'Software Engineering':
console.log('My favorite subject is Software Engineering.');
break;
case 'Programming':
console.log('My favorite subject is Programming.');
       break;
    default:
        console.log('My two favorite subjects are Software Engineering and  Programming.');
}

Output:

My favorite subject is Programming.

Here’s the explanation for the example code above:

The console will log “My favorite subject is Programming,” because the value of subject matches the “Programming” case.

After executing the console.log statement, it encounters the break keyword and immediately exits the switch block.

If the subject was “English” it would log “My two favorite subjects are Software Engineering and Programming,” because “English” does not match any of the cases and therefore the default case is executed.

Examples of Switch Statement

Here are a few more examples of using the switch statement in JavaScript:

Example 1: Using Switch for Multiple Cases

let day = new Date().getDay();
let dayName;

switch(day) {
    case 0:
        dayName = "Sunday";
        break;
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    case 6:
        dayName = "Saturday";
        break;
}

if(day === 0 || day === 6) {
    console.log('It is ' + dayName + ', the weekend!');
} else {
    console.log('It is ' + dayName + ', looking forward to the weekend.');
}

Output:

It is Wednesday, looking forward to the weekend.

Example 2: Using Switch to Route Function Calls

function performOperation(operation, a, b) {
switch(operation) {
case 'add':
return a + b;
case 'subtract':
return a - b;
case 'multiply':
return a * b;
case 'divide':
return a / b;
default:
return 'Invalid operation';
}
}

console.log(performOperation('add', 10, 30));

Output:

40

Example 3: Using Switch with Enums

const COLOR = {
RED: 'red',
BLUE: 'blue',
GREEN: 'green'
};

let color = COLOR.RED;

switch(color) {
case COLOR.RED:
console.log('The color is red.');
break;
case COLOR.BLUE:
console.log('The color is blue.');
break;
case COLOR.GREEN:
console.log('The color is green.');
break;
default:
console.log('Unknown color.');
}

Output:

The color is red.

Example 4: Using Switch to Implement State Machines

let state = 'idle';

switch(state) {
case 'idle':
console.log('Waiting for input…');
// Code to wait for input
break;
case 'loading':
console.log('Loading data…');
// Code to load data
break;
case 'processing':
console.log('Processing data…');
// Code to process data
break;
default:
console.log('Unknown state.');
}

Output:

Waiting for input…

Conclusion

To sum up, we have discussed the switch statement in JavaScript that is used to perform different actions based on different conditions.

It allows you to efficiently handle multiple cases and execute different actions for each condition. However, it’s crucial to use the “break” keyword to prevent unintended fall-through behavior.

Whether you’re routing function calls, working with enums, or implementing state machines, the switch statement provides a structured and readable way to manage conditional logic in your JavaScript code.

We hope this article has provided you with enough information to understand the JavaScript switch statement.

If you want to explore more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders 😊.

Leave a Comment