Peter Lyons Peter Lyons - 3 months ago 10
Javascript Question

switch statement and scopes in ES2015

Consider this ES2015 module and the behavior when run in node v6.4.0.

'use strict'

const outer = 1

switch ('foo') {
case 'bar':
const heyBar = 'HEY_BAR'
break
case 'baz':
const heyBaz = 'HEY_BAZ'
break
default:
const heyDefault = 'HEY_DEFAULT'
}
console.log(
outer, // 1, makes sense, same top-level scope
heyBar, // undefined. huh? I thought switch did NOT create a child scope
heyBaz, // undefined. huh? I thought switch did NOT create a child scope
heyDefault) // 'HEY_DEFAULT' makes sense


This seems internally inconsistent to me. If the switch statement did NOT create a lexical scope, I would expect all the
hey*
variables to be part of the main scope and to all behave consistently. If the switch statement did create a lexical scope, I would still expect them to be consistent, but the variables declared in the
case
clauses behave like they are in a child scope, whereas the variables in the
default
clause behaves like it is in the outer scope.

My question is are there any child scopes involved in a switch statement, and if so what are the details of how they behave?

mmm mmm
Answer

The switch statement didn't create a lexical scope. All the hey* variables are part of the main scope, if they weren't you'd get a ReferenceError: hey... is not defined. But you are only assigning a value to your hey* constants if the case is true, otherwise they remain just undefined.

Here's an example of an if statement, creating a scope

if (false) {
    const foobarbaz = 'hello'
}

console.log(foobarbaz);

// ReferenceError: foobarbaz is not defined