in , ,

JavaScript Switch Statement

JavaScript Switch Statement
JavaScript Switch Statement

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

Definition and Usage

The switch proclamation executes a block of code contingent upon various cases.

The switch statement is a part of JavaScript’s “Conditional” Statements, which are used to perform various activities dependent on various conditions. Use the switch to choose one of the numerous blocks of code to be executed. This is the perfect solution for since quite a while ago, nested if/else statements.

The switch statement evaluates an expression. The value of the expression is then contrasted and the values of each case in the structure. If there is a match, the related block of code is executed.

The switch statement is often used along with a break or a default watchword (or both). These are both discretionary:

The break catchphrase breaks out of the switch block. This will stop the execution of more execution of code or potentially case testing inside the square. In the event that break is excluded, the following code block in the switch articulation is executed.

The default catchphrase indicates some code to run if there is no case coordinate. There must be one default catchphrase in a switch. Despite the fact that this is discretionary, it is suggested that you use it, as it deals with sudden cases.


The JavaScript switch statement is used in decision making.

The switch statement evaluates an expression and executes the corresponding body that coordinates 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 equivalent to value1, its body is executed.
  • If the result of the expression is equivalent to value2, its body is executed.
  • This process goes on. If there is no coordinating 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 are also executed.
  • The default clause is also optional.

Flowchart of 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.

  • The expression’s result is evaluated with case 1 which results in false.
  • Then the switch statement goes to the second case. Here, the expression’s result matches with case 2. So The value is two is displayed.
  • The break statement terminates the block and the control flow of the program jumps to the 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, the switch statement checks the worth carefully. So the expression’s result doesn’t coordinate with the case “1”.
  • At that point, the switch statement goes to the subsequent case. Here, the expression’s result matches with case 1. So The value is one is shown.
  • The break statement ends the block and the control flow of the program leaps to the outside of the switch block.

Note: In JavaScript, the switch statement checks the cases carefully (should be of a similar data type) with the expression’s outcome. Notice in the above example, 1 doesn’t coordinate with “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
const operator = prompt('Enter operator ( either +, -, * or / ): ');

// take the operand input
const number1 = parseFloat(prompt('Enter first number: '));
const 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 the above program, the user is asked to enter either +, – , * or/, and two operands. At that point, the switch statement executes cases dependent on the user input.


JavaScript 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, different cases are gathered. All the gathered cases share a similar code.

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

JavaScript switch Without break
Switch Vs if…else Statement


Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.

salman khan

Written by worldofitech

Leave a Reply

How to Set Up Two WhatsApp Accounts on Android

The most effective method to Set Up Two WhatsApp Accounts on Android

Z Library | Download Any E-Book For Free| World Largest E-Library

Z Library | Download Any E-Book For Free| World Largest E-Library