Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are global let variables stored? [duplicate]

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?

like image 899
Akshay Gundewar Avatar asked Dec 24 '22 21:12

Akshay Gundewar


1 Answers

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).

like image 138
T.J. Crowder Avatar answered Jan 04 '23 19:01

T.J. Crowder