Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
54
rated 0 times [  60] [ 6]  / answers: 1 / hits: 51082  / 8 Years ago, tue, december 6, 2016, 12:00:00

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
}




More From » scope

 Answers
31

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 (...) ...
})();

[#59798] Saturday, December 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mercedez

Total Points: 525
Total Questions: 103
Total Answers: 102

Location: Trinidad and Tobago
Member since Fri, Mar 24, 2023
1 Year ago
;