JavaScript Lessons

JavaScript Switch Case: Handle Multiple Cases Easily

The JavaScript switch case statement is a cleaner alternative to long if else chains. See how to group multiple cases and keep your conditionals readable.

Serhat ALPASLAN2 min read

javascript

switch case in javascript is actually similar to using if else. We use it when using if else isn’t enough, that is, when we need to control more complex operations. Let’s look at the syntax of switch case in the example below.

switch(degisken/ifade) {
    case degisken1:  
        // code block for degisken1
        break;

    case degisken2:  
        // code block for degisken1
        break;

    case degiskenN:
        // code block for degisken N
        break;

    default:
        // code block for default
}

switch case evaluates the variable inside the parentheses and runs the relevant tasks based on the result.

  • If the result of the variable in switch is equal to degisken1, the code block for degisken1 is run
  • If the result of the variable in switch is equal to degisken2, the code block for degisken2 is run
  • If no case matches, the default code block is run.

The break statement inside switch is optional. If the break statement is used inside a code block, that code block ends after it runs. But the break statement
If the break statement is not used, the cases after the matching case are also executed.

let a = 2;

switch (a) {

    case 1:
        a = 'bir';
        break;
    case 2:
        a = 'iki';
        break;
    default:
        a = 'bunların dışında bir rakam';
        break;
}
console.log('Rakam : '+a );

Using Multiple Cases with JavaScript Switch

In switch usage, you can use the case statement in a way that shares the same code. Let’s look at the example below for this.

// using multiple cases
let yiyecek = 'elma';
switch(fruit) {
    case 'elma':
    case 'muz':
    case 'armut':
        console.log(yiyecek +' bir meyvedir');
        break;
    default:
        console.log(yiyecek +' bir meyve değildir.');
        break;
}

Share it if it helped

Write a comment