Peter Lyons Peter Lyons - 1 year ago 73
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'
case 'baz':
const heyBaz = 'HEY_BAZ'
const heyDefault = 'HEY_DEFAULT'
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
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
clauses behave like they are in a child scope, whereas the variables in the
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 Source

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'


// ReferenceError: foobarbaz is not defined
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download