Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Can I declare variables inside switch cases? [duplicate]

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.

like image 332
PRIX Avatar asked Sep 18 '15 08:09

PRIX


1 Answers

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;
}
like image 116
Ashkan Mobayen Khiabani Avatar answered Nov 05 '22 09:11

Ashkan Mobayen Khiabani