0

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:

enter image description here

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.

enter image description here

How to understand this behave of the code? That would be very much appreciated with related specs provided. Thank you!

krave
  • 1,629
  • 4
  • 17
  • 36
  • Actually switch is temporaryly overriding the function definition inside its scope. It releases the definition to the original function definition when its scope ends. – Helio Sep 09 '22 at 10:41
  • https://stackoverflow.com/questions/42434297/function-declaration-in-a-switch-why-does-only-the-last-definition-remain – Reynadan Sep 09 '22 at 11:02
  • @Reynadan Thanks for the info. I know the fact that last declaration overrides the previous ones. So I didn't ask about that. My first example in the question also shows that the answer you refer to is not very correct because only matched case clause make its declaration available in global scope. Not other case clauses. My main concern is why function declarations in non-matched case clauses hoisted only inside the scope created by `switch` and why matched case clause can make the declaration available in the global scope. – krave Sep 09 '22 at 15:52

0 Answers0