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
When code is running in
script
tag it will use global scope. For global scope v8 creates oneEnvironment Record
to which youra
identified is assigned. That’s why differentscript
tags have the samea
value.Where to read about it: https://tc39.es/ecma262/#sec-let-and-const-declarations
and https://tc39.es/ecma262/#sec-environment-records
If you want to restrict the scope of that
a
variable to the first<script>
element, then wrap the content in a block statement: