This question already has an answer here:
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?
Because you used
let
rather thanvar
, 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
, andclass
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).