#Why Does This Happen?

If you specify the same variable name (created using let, const or var) within case/default in a switch statement, then it may result in a SyntaxError (as shown in the example below):

const type = 2;

switch (type) {
    case 1:
        let foo = 'bar';
        console.log(foo);
        break;

    case 2:
        // SyntaxError: Identifier 'foo' has already been declared
        let foo = 123;
        console.log(foo);
        break;

    // ...
}

This happens because:

#How to Fix the Issue?

To fix this issue, you can do either of the following:

For example, you can wrap each case/default clause with curly braces ({}), like so:

// ES6+
const type = 2;

switch (type) {
    case 1: {
        let foo = 'bar';
        console.log(foo);
        break;
    }

    case 2: {
        let foo = 123;
        console.log(foo);
        break;
    }

    // ...
}

// output: 123

This will give each case/default its own block scope, preventing issues with variable shadowing.