JavaScript tutorials for Beginners – JavaScript Switch Statement

 

 

(JavaScript Tutorials for Beginners)

In this end-to-end example, you will learn – JavaScript tutorials for Beginners – JavaScript Switch Statement.

JavaScript Switch Statement

In this tutorial, you will learn about the JavaScript switch statement with the help of examples.

The JavaScript switch statement is used in decision making.

The switch statement evaluates an expression and executes the corresponding body that matches the expression’s result.

The syntax of the switch statement is:

switch(variable/expression) {
    case value1:  
        // body of case 1
        break;

    case value2:  
        // body of case 2
        break;

    case valueN:
        // body of case N
        break;

    default:
        // body of default
}

The switch statement evaluates a variable/expression inside parentheses ().

  • If the result of the expression is equal to value1, its body is executed.
  • If the result of the expression is equal to value2, its body is executed.
  • This process goes on. If there is no matching case, the default body executes.

Notes:

  • The break statement is optional. If the break statement is encountered, the switch statement ends.
  • If the break statement is not used, the cases after the matching case is also executed.
  • The default clause is also optional. It can also be declared inside in the beginning or in the middle of the switch block.

Flowchart of switch Statement

Flowchart of JavaScript switch statement
Flowchart of JavaScript switch statement

Example 1: Simple Program using switch Statement

// program using switch statement
let a = 2;

switch (a) {

    case 1:
        a = 'one';
        break;

    case 2:
        a = 'two';
        break;

    default:
        a = 'not found';
        break;
}
console.log(`The value is ${a}`);

Output

The value is two.

In the above program, an expression a = 2 is evaluated with a switch statement.

  • An expression’s result is evaluated with case 1 which results in false.
  • Then the switch statement goes to the second case. Here expressions’s result matches with case 2. So The value is two is displayed.
  • The break statement terminates the block and control flow of the program jumps to outside of the switch block.

Example 2: Type checking in switch Statement

// program using switch statement
let a = 1;

switch (a) {
    case "1":
        a = 1;
        break;

    case 1:
        a = 'one';
        break;

    case 2:
        a = 'two';
        break;

    default:
        a = 'not found';
        break;
}
console.log(`The value is ${a}`);

Output

The value is one.

In the above program, an expression a = 1 is evaluated with a switch statement.

  • In JavaScript, switch statement checks the value strictly. So the expression’s result does not match with case "1".
  • Then the switch statement goes to the second case. Here expressions’s result matches with case 1. So The value is one is displayed.
  • The break statement terminates the block and control flow of the program jumps to outside of the switch block.

Note: In JavaScript, the switch statement checks the cases strictly(should be of the same data type) with the expression’s result. Notice in the above example, 1 does not match with the “1”.


Let’s write a program to make a simple calculator with the switch statement.

Example 3: Simple Calculator

// program for a simple calculator
let result;

// take the operator input
let operator = prompt('Enter operator ( either +, -, * or / ): ');

// take the operand input
let number1 = parseFloat(prompt('Enter first number: '));
let number2 = parseFloat(prompt('Enter second number: '));

switch(operator) {
    case '+':
         result = number1 + number2;
        console.log(`${number1} + ${number2} = ${result}`);
        break;

    case '-':
         result = number1 - number2;
        console.log(`${number1} - ${number2} = ${result}`);
        break;

    case '*':
         result = number1 * number2;
        console.log(`${number1} * ${number2} = ${result}`);
        break;

    case '/':
         result = number1 / number2;
        console.log(`${number1} / ${number2} = ${result}`);
        break;

    default:
        console.log('Invalid operator');
        break;
}

Output

Enter operator: +
Enter first number: 4
Enter second number: 5
4 + 5 = 9

In above program, the user is asked to enter either +* or /, and two operands. Then, the switch statement executes cases based on the user input.


switch with Multiple Case

In a JavaScript switch statement, cases can be grouped to share the same code.

Example 4: switch with Multiple Case

// multiple case switch program
let fruit = 'apple';
switch(fruit) {
    case 'apple':
    case 'mango':
    case 'pineapple':
        console.log(`${fruit} is a fruit.`);
        break;
    default:
        console.log(`${fruit} is not a fruit.`);
        break;
}

Output

apple is a fruit.

In the above program, multiple cases are grouped. All the grouped cases share the same code.

If the value of the fruit variable had value mango or pineapple, the output would have been the same.

 

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!