JavaScript: Can I declare variables inside switch cases?

PRIX picture PRIX · Sep 18, 2015 · Viewed 9.2k times · Source

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.

Answer

Ashkan Mobayen Khiabani picture Ashkan Mobayen Khiabani · Sep 18, 2015

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;
}