7

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.

7
  • 3
    Simple answer is Yes Commented Sep 18, 2015 at 8:23
  • 1
    javascript es5 only has function scope, a will be local to the function, not to the switch Commented Sep 18, 2015 at 8:25
  • @Hacketo So, Javascript can only have scopes within the global and functions? Commented Sep 18, 2015 at 8:39
  • @PRIX using var, yes. you can see many examples in the linked post Commented Sep 18, 2015 at 8:43
  • 1
    Note that you cannot declare the same variable in different cases because there is only one underlying block. Commented Dec 28, 2016 at 3:58

1 Answer 1

8

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.