javascriptscopeswitch-statement

Javascript scope variable to switch case?


In C you can scope a variable to a switch case, like this.

With javascript I get unexpected token using the following:

const i = 1

switch (i) {
    // variables scoped to switch
    var s
    var x = 2342
    case 0:
      s = 1 + x
      break
    case 1:
      s = 'b'
      break
}

Is there another way to do this or should I just declare my variables outside the switch?

EDIT:

This is a workaround I considered but it didn't end up working. The reason being that each case has its own scope.

const i = 1

switch (i) {
    case i:
      // variables scoped to switch
      var s
      var x = 2342
    case 0:
      s = 1 + x
      break
    case 1:
      s = 'b'
      break
}


Solution

  • Since var creates variables at function scope anyway, using it is pretty pointless. For this to work at a granularity below function scopes you'll have to use let and a browser/compiler which supports it, and then introduce a new block which you can scope things to (within switch it's simply invalid syntax):

    if (true) {
        let s;
    
        switch (i) {
            ...
        }
    }
    

    This scopes s to the if block, which for all intents and purposes is identical to the "switch scope" here.

    If you cannot support let, you'll need to use an IIFE:

    (function () {
        var s;
    
        switch (...) ...
    })();