Leonard Niehaus
Leonard Niehaus

Reputation: 530

Access variables declared inside JavaScript switch statement from outside

Why does

switch ("string") {
  case "string":
    const text = "Hello World!"
    break
}

console.log(text)

return error: Uncaught ReferenceError: text is not defined ?

I don't understand why the variable text returns undefinded.

Upvotes: 1

Views: 2017

Answers (2)

Geshode
Geshode

Reputation: 3764

Because it is not in the same scope. Something like this should work:

let text
switch ("string") {
  case "string":
    text = "Hello World!"
    break
}

console.log(text)

Upvotes: 2

Evis Cheng
Evis Cheng

Reputation: 91

Declaring a variable with const is similar to let when it comes to Block Scope.

The x declared in the block, in this example, is not the same as the x declared outside the block:

var x = 10;
// Here x is 10
{ 
  const x = 2;
  // Here x is 2
}
// Here x is 10

https://www.w3schools.com/js/js_const.asp

Upvotes: 1

Related Questions