1

I was going through Lexical environment and environment record / scope in JS.

I know difference (partly) between var and let (one being block scoped, while one being functional scope) and also the let being in TDZ before being assigned any variable.

I executed the following piece of code but now I am little bit confused.

Code Snippet

Confusion : In global code, var a is assigned to GLOBAL scope because its a var, while let b is being hoisted in a separate memory space (Here being the Script Scope). So we cannot access it before being initialized (TDZ).

But same concept when I am writing it in the function, we only have one scope which is the Local Scope of that function, then how is JS knowing the difference between a1 and b1 ? When I am running debugger both are setting to undefined (in creation phase) and both are being set to 1 during their execution phase. Like we are not having two different scope unlike a and b right ?

Also can some explain what is Script in Scope (or atleast give any reference for it where I can see it)

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 2
    The "script scope" is actually a global scope as well. The only difference is that it is not backed by an object (the global `window` object). But this nesting of scopes is more like an implementation detail. "*How is JS knowing the difference between `a1` and `b1`*" - by looking at the declaration or some other metadata about the type of the variable, which is also stored in the code/scope but now shown in the debugger. That's also how it distinguishes between `let` and `const` for example. – Bergi Jun 25 '23 at 23:54
  • Okay understood the part where we are having a Script scope, because any var variables are appended to the global object which cannot be done for let case. However are you saying that when being in a function, there is no clear way to debug let and var actually, since both will have same scope? – Sourish Mukherjee Jun 26 '23 at 02:59
  • Yes. The scopes are not created for distinguishing between `let` and `var` (and other declarations), that is done just by executing different code and creating different kinds of bindings (e.g. mutable vs immutable). The scopes are only created if you can actually have two separate variables with the same name in them, which doesn't ([normally](https://stackoverflow.com/q/76508953/1048572)) happen in functions – Bergi Jun 26 '23 at 08:54

0 Answers0