0

I'm trying to understand exactly how does different declarations are being bound to Lexical Environment's Environment Record of block and function scope.

Consider the following code:

function myFunc() {
    if(true) {
        let first = "first";
        const second = "second ";
        var third = "third ";    
        function fourth() { }
    }

    console.log(first);  // ReferenceError
    console.log(second); // ReferenceError
    console.log(third ); // "third"
    console.log(fourth); // "function fourth.."
}

As for the var declaration, for my knowledge its being bound to the Environment Record of the Execution Context's VariableEnvironment component, which means the binding exists inside the Lexical Environment of the "myFunc" function.

But what about the declared function "fourth"? Does the Lexical Environment of the if statement (Block Scope) creates some sort of a different Environment Record that only bounds let and const declarations?
Please refer to ECMAScript in your answer if possible.

  • Just use strict mode and it will behave as expected :-) – Bergi Apr 07 '20 at 20:47
  • I'm actually not trying to solve this, just trying to understand the behavior with relation to the Environment Record of the Lexical Environment, according to the specs. – Ran Roslan Bobkov Apr 07 '20 at 21:05
  • 1
    Sure, see the linked duplicate for that. But for the normal behaviour, where the function is declared in the lexical environment, use strict mode, and you'll get a reference error for `fourth` as well. – Bergi Apr 07 '20 at 21:31
  • Oh I see, in non-strict the function is being bound to both block and functional Environment Records, Thanks. – Ran Roslan Bobkov Apr 09 '20 at 20:36

0 Answers0