4

I have created a navigator variable in global scope and assign it a string using let keyword.

// in a browser
    let navigator = "Hello!";
    console.log(navigator );                       // "Hello!"
    console.log(window.navigator === navigator );  // false

Here let navigator value shadows the window.navigator. But I am very curious to know where exactly the let navigator gets stored in?

Akshay Gundewar
  • 864
  • 11
  • 30
  • 1
    Mozilla describes it [here](https://hacks.mozilla.org/2015/07/es6-in-depth-let-and-const/) like this: `Global let ... live in the scope of an invisible block that notionally encloses all JS code that runs in a web page.` – Jaromanda X Jan 25 '17 at 09:41

1 Answers1

11

Because you used let rather than var, it gets stored in the declarative environment record associated with the global lexical environment object, rather than on the global object itself. Environment records and lexical environment objects are specification mechanisms and not directly accessible in code (and thus the actual implementations of them can vary depending on JavaScript engine).

This is a concept — globals that aren't properties of the global object — is a new thing introduced as of ES2015; until then, all globals were properties of the global object. As of ES2015, global-level let, const, and class identifier bindings are not held on the global object, but instead on a separate declarative environment record.

Environment records and lexical environment objects are the same mechanisms used (both in ES2015+ and in ES5 and earlier) for storing local variables within a function.

The global aspect of this is defined in §8.2.3 - SetGlobalRealmObject, which in turn references §8.1.2.5 - NewGlobalEnvironment(G, thisValue).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 2
    Is there a way to inspect all the variables in lexical scope? Like the way, we can `console.log(window)` and see all the associated variables. – Akshay Gundewar Jan 25 '17 at 09:45
  • 2
    @GAkshay: Nope. That's part of why they were moved off the global object, to make them non-discoverable. Along with the addition of modules, the goal is to move away from using the global object for everything. – T.J. Crowder Jan 25 '17 at 09:48
  • (I should have known this would have been covered by an answer to a previous question.) – T.J. Crowder Jan 25 '17 at 10:01