How to use a variable name declared with let inside multiple switch cases?

Viewed 3322

I'm trying use switch statement to perform a task. I have declared a variable using let in first case. But when i try to access it in second case it says "Uncaught ReferenceError: t is not defined"

x = "20";
switch (x) {
  case '10':
    let t = 15;
    break;
  case '20':
    console.log(t);
}

I get this error

Uncaught ReferenceError: t is not defined at :6:21

but if i try to declare same variable in second case then

x = "20";
switch (x) {
  case '10':
    let t = 15;
    break;
  case '20':
    let t = 150;
    console.log(t);
}

i get this error

Uncaught SyntaxError: Identifier 't' has already been declared

why is this happening? how to solve this issue without using var and without declaring variable with different name. Thanks in Advance.

1 Answers

If you declare the variable in case '10' and you are trying to access the variable in case '20', you will get that error because you have not declared the variable in the scope of case '20'.

If you declare the variable multiple times in different cases then the compiler will understand that you are trying to declare the variable multiple times; so, it gives you that error.

This is what it should be. You declare it before the switch statement. Therefore, the variable is usable in every case beneath the switch.

x = "20";
    let t = 0;
    switch (x) {
        case '10':
        t = 15;
        break;
    case '20':
        t = 150;
        console.log(t);    
    }

Related