6

In C language, you cannot declare any variables inside 'case' statements.

switch ( i ){
case 1:
  int a = 1; //error!
  break;
}

However, you can when you use with curly parentheses.

switch ( i ){
case 1:
  {// create another scope.
    int a = 1; //this is OK.
  }
  break;
}

In Javascript case, can I use var directly inside case statements?

switch ( i ){
case 1:
  var a = 1
  break
}

It seems that there is no error but I'm not confident this is grammatically OK.

PRIX
  • 73
  • 1
  • 1
  • 4
  • 3
    Simple answer is __Yes__ – Satpal Sep 18 '15 at 08:23
  • 1
    javascript es5 only has function scope, `a` will be local to the function, not to the switch – Hacketo Sep 18 '15 at 08:25
  • @Hacketo So, Javascript can only have scopes within the global and functions? – PRIX Sep 18 '15 at 08:39
  • @PRIX using `var`, yes. you can see many examples in the linked post – Hacketo Sep 18 '15 at 08:43
  • @Hacketo Wow, very useful link! Thank you! – PRIX Sep 18 '15 at 08:45
  • @satpal agreed yes you can but it's not really good practice, they get hoisted so better to declare earlier and make sure they don't break or redeclare or even predeclare anything imho – StudioTime Jul 17 '16 at 21:47
  • 1
    Note that you cannot declare the same variable in different `case`s [because there is only one underlying block](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone_and_errors_with_let). – Franklin Yu Dec 28 '16 at 03:58

1 Answers1

7

Yes in javascript you can do this but I think testing it would be much simpler:

Fiddle

var i = 1;
switch ( i ){
case 1:
  var a = 1;
  alert(a);
  break;
}
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171