While creating JavaScript with ASP.NET MVC I noticed several scope warnings and realized that I am missing something with understanding the variable scope inside the switch / case statement.
Warning: 'i' is already defined referring to case b and case c
My code looks similar to this:
switch(element) {
case 'a':
for(var i=0; i < count; i++){
do something
}
break;
case 'b':
for(var i=0; i < count; i++){
do something
}
break;
case 'c':
for(var i=0; i < count; i++){
do something
}
break;
}
Javascript does not use block scope.
Therefore, all local variables are in scope throughout the entire function in which they were declared.
However, in your particular case, there is no C-like language (that I know of) in which each case
statement forms an independent scope.
For example, the following C# code will not compile:
switch(someVar) {
case 1:
int a;
break;
case 2:
int a; //'a' is already defined
break;
}