Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What object are Javascript global variables stored in?

Are global variables stored in specific object? For instance:

var test="stuff";
console.log(window.test);
console.log(document.test);
console.log(this.test);

All three of these tests result in undefined, so is there an object that holds these variables?

I feel as though this is something stupid that I should already know, but I can't even seem to find the answer online.

like image 336
twiz Avatar asked Jul 20 '12 04:07

twiz


People also ask

Where do global variables get stored?

Global variables are stored in the data section. Unlike the stack, the data region does not grow or shrink — storage space for globals persists for the entire run of the program.

What is JavaScript global object?

A global object is an object that always exists in the global scope. In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (In Node. js this is not the case.)

Where are let variables stored in JavaScript?

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.


1 Answers

Here is a late but technical answer.

You ask

Are global variables stored in specific object?

The answer is yes; they are stored in something called, officially, the global object. This object is described in Section 15.1 of the official ECMAScript 5 Specification.

The global object is not required to have a name; but you can refer to its properties, such as String, isNaN, and Date simply by using their name. Your JavaScript host environment will place other properties in the global object besides the ones required by the ECMAScript specification, such as alert or console. In a browser, I can write the script

alert("Hello world");

because alert is a property of the global object.

Note that there does not have to be a way to access this global object at all, believe it or not. The cool thing, however, is that many host environments will put a property in the global object whose value is a reference to the global object itself. In most web browsers, this property is called window. So we can write:

alert("Hello");
window.alert("Hello");
window.window.alert("Hello");
window.window.window.window.window.alert("Hello");

and you can also say:

var x = 5;
alert(this.x);

and get 5 alerted.

like image 165
Ray Toal Avatar answered Oct 07 '22 15:10

Ray Toal