Here is the code
switch (0) {
case 0:
console.log("Case 0 started");
foo();
console.log("Case 0 ended");
break;
case 1:
function foo() { console.log("foo is a function") }
break;
}
console.log("But here foo is:", foo);
foo();
Here is the output of the code:
Based on the output, it seems that function foo
being declared even in a case which is impossible to be hit because 1 !== 0
forever. And foo
is only available in the scope of the switch case
block. It is not accessible from the top level as we can tell from line 13 of the code. foo
is undefined.
But if we make some change to the code by adding another declaration like this:
switch (0) {
case 0:
console.log("Case 0 started");
// Add this declaration.
function foo() { }
foo();
console.log("Case 0 ended");
break;
case 1:
function foo() { console.log("foo is a function") }
break;
}
console.log("But here foo is:", foo);
foo();
foo
is available in the top level scope.
How to understand this behave of the code? That would be very much appreciated with related specs provided. Thank you!