Open In App

How to Redeclare a Variable Inside a Switch Block in JavaScript ?

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Generally, in JavaScript, if you try to declare a variable with the same name inside a switch block will throw a syntaxError for declaring the variable again in the same block using the let keyword. We can overcome this problem by enclosing the code for every case statement inside a block using the curly brackets({}) and then redeclare the variables inside that code block using the let keyword. Enclosing the code inside the curly brackets will create the different scopes which allows you to declare variables with the same names in each one of them.

Example: The below code example will explain to you how you can redeclare the variables inside a switch block.

Javascript




const str = "GFG";
switch(str){
    case "gfg": {
        let name = "gfg";
        console.log(name);
        break;
    }
    case "GFG": {
        let name = "GFG";
        console.log(name);
        break;
    }
    default:
        console.log("GeeksforGeeks");
}


Output

GFG

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads