Thursday 1 June 2017

JavaScript: Can I declare variables inside switch cases?




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



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
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...