switch statement in JavaScript

testYourselfJavaScript JavaScript switch143

JavaScript has several conditional statements, one of them is the switch statement.

Conditional statements are one of the most useful and common elements of all programming languages. They allow a specific block of code to be executed only if a specific condition is matched.

if (count === 0) {
    console.log("the basket is empty");
}

The switch statement is a type of conditional statement that executes a given expression and compares its result with several specified values.

Using the switch statement in JavaScript

Nothing prevents you from using many if...else statements, although this is not always the best solution. Whenever we deal with writing many if...else statements, we can replace them with one switch statement.

var day = 2;
var weekDay;
if (day === 0) {
    weekDay = 'Monday';
} else if (day === 1) {
    weekDay = 'Tuesday';
} else if (day === 2) {
    weekDay ='Wednesday';
} else if (day === 3) {
    weekDay = 'Thursday';
} else if (day === 4) {
    weekDay = 'Friday';
} else if (day === 5) {
    weekDay = 'Saturday';
} else if (day === 6) {
    weekDay = 'Sunday';
}
console.log(weekDay); // 'Wednesday'

The switch statement in JavaScript is used to check several conditions and perform different actions based on a comparison result. It lets you choose one of many blocks of code that will be executed.

var day = 2;
var weekDay;
switch(day) {
    case 0:
        weekDay = 'Monday';
        break;
    case 1:
        weekDay = 'Tuesday';
        break;
    case 2:
        weekDay ='Wednesday';
        break;
    case 3:
        weekDay = 'Thursday';
        break;
    case 4:
        weekDay = 'Friday';
        break;
    case 5:
        weekDay = 'Saturday';
        break;
   case 6:
        weekDay = 'Sunday';
        break;
}
console.log(weekDay); // 'Wednesday'

The switch statement is a much more efficient way to write statements that check many conditions. Its syntax is simpler than the complicated series of several if...else statements.

How does the switch statement work?

  • the switch statement in JavaScript execute the input expression in parentheses
  • the value of the expression is compared to the values ​​of each case clause
  • if a match is found, the associated code block is executed until the break or return keyword is found or the switch statement ends
  • if there is no matching case clause, the code assigned to the default clause will be used
  • if the default clause is not found, then the switch statement will end and the program will go to the code placed after the switch statement

If multiple case clauses match the value of an expression, the first case clause is selected.

var nr = 1;
switch(nr) {
    case 1:
        console.log("Number 1 is selected");
        break;
    case 1:
        console.log("Number one is selected");
        break;
}

Execution of the above code will display the message "Number 1 is selected" in the console. The code assigned to the second case clause will not be executed.

Break

The break keyword indicates the end of a specific case clause. When JavaScript reaches the break keyword, it will stop executing code inside the switch statement.

If we omit the break keyword, the code associated with the next case clause will be executed, even if the value of the next case does not match the expression.

var nr = 1;
switch(nr) {
    case 1:
        console.log("Number 1 is selected");
    case 2:
        console.log("Number 2 is selected");
        break;
}

Execution of the above code will display both the following message in the console: "Number 1 is selected" and "Number 2 is selected".

In addition, it is worth knowing that we do not have to add the break keyword in the last clause of the switch statement in JavaScript - execution of the statement will be completed regardless of whether the break keyword will be added or not.

Default

The default keyword defines the code to be run if none of the case clauses matches the expression. The default keyword in the switch statement is optional.

var country = 'France';
var currency;
switch (country) {
    case 'England':
        currency = 'GBP';
        break;
    case 'Poland':
        currency = 'PLN';
        break;
    case 'Russia':
        currency = 'RUB';
        break;
    default:
        currency = 'EURO';
}
console.log(currency); // 'EURO'

In the given example, none of the case clause matches the input value, so the default clause will be executed.

In a switch statement in JavaScript, the default keyword does not need to be last. It can be at the beginning or in the middle of the switch statement.

var country = 'France';
var currency;
switch (country) {
   default:
        currency = 'EURO';
        break;
    case 'England':
        currency = 'GBP';
        break;
    case 'Poland':
        currency = 'PLN';
        break;
    case 'Russia':
        currency = 'RUB';
        break;
    
}
console.log(currency); // 'EURO'

Grouping cases

The case clauses can be combined to execute the same block code. In this situation, the order in which the case clauses are placed does not matter.


var input = 'Hello';
var answer;
switch(input) {
    case 'Hi':
    case 'Hello':
        answer = "Hi";
        break;
    case 'Bye':
        answer = 'Goodbye';
        break;
}
console.log(answer); // 'Hi'

The ability to group case clauses is a side effect of how the switch statement in JavaScript works without using the break keyword.

Expressions and values

The switch statement in JavaScript allows you to use both values and expressions, regardless of whether it is a switch statement declaration or a case clause.

var x = 3;
switch(x % 2) {
    case 0:
        console.log("the number is divisible by 2");
        break;
    case 1:
        console.log("the number is not divisible by 2");
}

The above example will execute the expression, compare the result with the values of the case clauses and display the message "the number is indivisible by 2".

Strict comparison

When comparing the input value of the switch statement with individual values of the case clauses, a strict comparison (===) is used - the values must have the same value and have the same type.

var error = '404';
var message;
switch(error) {
    case 404:
        message = 'Not found';
        break;
    case 500:
        message = 'Internal server error';
        break;
    default:
        message = 'Unknown error';
}
console.log(message); // 'Unknown error'

The above switch statement will compare the value of '400' and 400, which will give false, so the variable message will receive the value set in the default clause - 'Unknown error'.

Summary

  • The switch statement in JavaScript is a conditional statement that can be used to check several conditions and perform various actions based on a comparison result
  • the break keyword will stop code execution inside the switch statement
  • the default keyword defines the code that will be executed if none of the conditions of the switch statement match the expression
  • the default keyword does not have to be at the end of the switch statement - it can be placed at the beginning or in the middle of the switch statement
  • case clauses can be grouped to execute the same block of code
  • the switch statement in JavaScript lets you use values and expressions
  • when comparing the input value with case conditions, strict comparison is used (===)