1

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.

Leonard Niehaus
  • 500
  • 6
  • 16
  • 3
    As you know `const` is block scoped. Since you have the brackets around the `switch`, `const` won't be accessible outside them. However, you can delcare a `let` outside and assign its value inside the `case` statement – Panther Aug 27 '19 at 02:02
  • 1
    You have just stumbled on what a scoped variable is. Just so you can play around, create the variable text outside the switch, and set its value inside the switch. – Spangle Aug 27 '19 at 02:04

2 Answers2

2

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)
Geshode
  • 3,600
  • 6
  • 18
  • 32
1

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

Evis Cheng
  • 91
  • 3