skip to Main Content

Consider following code snippet:

<script> 
let a=1; 
console.log(a); //prints 1
</script> 
<script> 
console.log(a);  //prints 1
</script> 

I want to ask if a is block scoped due to the declaration by let which means it is scoped to single <script> tag the why a in second script tag is printing value 1?

2

Answers


  1. When code is running in script tag it will use global scope. For global scope v8 creates one Environment Record to which your a identified is assigned. That’s why different script tags have the same a value.

    Where to read about it: https://tc39.es/ecma262/#sec-let-and-const-declarations
    and https://tc39.es/ecma262/#sec-environment-records

    A Global Environment Record is used for Script global declarations. It does not have an outer environment; its [[OuterEnv]] is null. It may be prepopulated with identifier bindings and it includes an associated global object whose properties provide some of the global environment’s identifier bindings. As ECMAScript code is executed, additional properties may be added to the global object and the initial properties may be modified.

    Login or Signup to reply.
  2. If you want to restrict the scope of that a variable to the first <script> element, then wrap the content in a block statement:

    <script> 
    {
      let a=1; 
      console.log(a); //prints 1 
    }
    </script> 
    <script> 
      console.log(a);  //Uncaught ReferenceError: a is not defined
    </script> 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search