Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

JavaScript Switch Statement

The switch statement is similar to multiple if conditions. It allows us to set a condition then evaluate it against multiple values then decide on the execution path depending on the match that was found. Just like the if statement, it has the default fallback if no case is matched. If you have if statements with multiple conditions, then it is probably a good idea to use a switch statement instead. This will improve your program readability and performance.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - we will be executing JavaScript files directly using NodeJS from the command line. Alternatively you can execute the files in the web browser but that takes a a little more time and involves working with multiple programs.
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called javascript-switch

Open the directory javascript-switch in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • switch.js - this file will be used to for code dealing with the switch statement

The following visualizes our project setup

javascript-switch
-switch.js

Open the directory javascript-switch in Visual Studio Code or your favorite code editor

Switch statement syntax

The syntax for the switch statement is as follows

switch(value){
	case 'possible_value_1':
		//do something
		break;
        
    case 'possible_value_2':
        //do something
        break;
}

HERE,

  • switch(value){...} the keyword switch is used to start the switch statement. The value to be evaluated value is placed within parenthesis () just after the switch statement. The code block for the switch statement is placed between {...} curly brackets.
  • case 'possible_value_1': the case statement is used to define a possible value of value which is the argument that is passed to the switch statement. The case statement is ended using a : full colon. //do something specifies the action to be taken if the value matches possible_value_1. The break statement is used to terminate the switch statement. If you do not include the break statement then all cases will be evaluated.
  • case 'possible_value_2': defines the second possible value of value and what action should be taken if this evaluates to true.

If you need more clarifications then you can use the comments section below to ask and we will respond.

JavaScript Switch Example

Now that we have looked at the syntax for the switch statement, let us look at a practical example. We will refactor the program that we created with multiple if statements in the previous lesson to use a more efficient switch statement.

Open the file switch.js that we created in the project setup above.

Add the following code.

let day = 'Sunday';

switch (day){
    case 'Saturday':
        console.log('Time to party');
        break;

    case 'Sunday':
        console.log('Relax');
}

HERE,

  • let day = 'Sunday'; defines a variable day that is initialized to the value Sunday
  • switch(day){...} defines our switch statement
  • case 'Saturday': checks if the value of the variable day is Saturday. If this is true then the code block below the case statement is executed. If this is false, the program evaluates the next case condition.
  • case 'Sunday': checks if the value of day is Sunday then takes the necessary action.

Open the terminal in Visual Studio Code then run the following command

node switch.js

You should be able to get the following results

Relax

Its now modify the value of the variable day to the following

let day = 'Wednesday';

The rest of the code remains the same as in the above section. Running our JavaScript file using node should display nothing in the terminal. This is because our value did not match any case that we defined in the switch statement.

In the next section, we will fix this problem so that our program is able to give feedback to the user when all cases fail to match.

JavaScript Switch Default statement

Let's now modify the above code to the following

let day = 'Wednesday';

switch (day){
    case 'Saturday':
        console.log('Time to party');
        break;

    case 'Sunday':
        console.log('Relax');

    default:
        console.log('Time to work');
}

HERE,

  • let day = 'Wednesday' initializes our variable day to the value Wednesday
  • switch(day){...} starts our switch statement.
  • default: the keyword default is used to specify the action that should be taken when no condition evaluates to true. For our example, we just print out the message Time to work if the day is not Sunday or Saturday.

Open the terminal and then run the following command

node switch.js

You should be able to get the following results

Time to work

JavaScript Console Menu Using Switch Statement

let's now look at a simple example that displays a menu in the console and allows the select to select a number that corresponds to the menu. We will then display what menu was selected by the user.

Create a new file menu.js in our project directory javascript-switch

Add the following code

console.log('User contacts management system');
console.log('-------------------------------');
console.log('Please select a menu number');
console.log('1. Display All Contacts');
console.log('2. Search Contacts');
console.log('3. Add New Contact');
console.log('4. Update Contact');
console.log('5. Delete Contact');
console.log('6. Exit Application');

function processSelection(menu){
    switch(menu){
        case 1:
            console.log('Display All Contacts');
            break;

        case 2:
            console.log('Search Contacts');
            break;

        case 3:
            console.log('Add New Contact');
            break;

        case 4:
            console.log('Update Contact');
            break;

        case 5:
            console.log('Delete Contact');
            break;

        case 6:
            console.log('Exit Application');
            break;

        default:
            console.log('You entered an invalid selection');
    }
}

const getinput = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

getinput.question(`Enter your menu selection: `, (menu) => {
    selection = parseInt(menu);
    processSelection(selection);
    getinput.close()
});

Summary

The switch statement is used to evaluate multiple conditions using the case statement. It is better to use the switch statement instead of if statements with multiple statements. The break keyword is used to step out of the switch statement. The default keyword is used to define the code block that should be executed if no condition is matched.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

JavaScript If Statement

JavaScript For Loop

Leave A Reply