I tried to implement a function using a switch, because I wanted to implement it differently, depending on the case. In a simple form, this is what it looks like:
function test() { console.log('hello world'); };
someVar = 'foo';
switch (someVar) {
case 'foo':
console.info('foo');
function test() { console.log('foo'); };
break;
case 'bar':
console.info('bar');
function test() { console.log('bar'); };
break;
default:
console.info('default');
function test() { console.log('default'); };
}
test();
Now, the console says 'foo'
, but if you have a look at the source code of test
, it will be function test() { console.log('default'); }
. This is not a scoping issue though, since a switch does not have its own scope, plus the function's first declaration is before the switch.
However, if test
is declared as a var
and initialized in the cases, the result will be as desired.
But why is always the last function declaration implemented, independent from which case is actually executed?