How to Fix "Identifier '...' has already been declared" JavaScript switch/case Error?

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.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.