Diego Perdomo
Diego Perdomo

Reputation: 463

Why is there a global object in Javascript?

I know that when we create a variable using the var keyword there is a property with the same name added to the window object (in a browser enviroment) but this creates (for me) a confusion, because I have to think about a normal global variable vs global object. Variables created with let keyword are not added to the global object and that creates a divergence between our global scope and the global object. So, why is this global object necessary in the first place? Why do something like window.x instead of using x directly. What is the difference between the global scope and global object?

Upvotes: 1

Views: 818

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138257

I cannot read the mind of Brendan Eich, but I can take an educated guess as to why the global object exists:

First of all, the design of JavaScript is kept very simple: Records (the place where variable values get stored) and Objects are very similar. Both are basically a collection of key-value pairs. That simplifies the design (e.g. a = 1 works the same way as a.b = 1) and has the side effect that objects can easily be used as records (e.g. with the with statement).

Secondly you might also want to refer to global variables although the variable got shadowed. That can easily be achieved with having a self reference inside the global object / record (window is just a self reference).

Therefore it does make sense that var creates a variable in the global record, which, you can also refer to via window..

Actually that const and let do not create a variable on the global scope is the inconsistency, but with that modularity gets achieved.

Upvotes: 0

D. Pardal
D. Pardal

Reputation: 6587

Why

It's hard to say exactly why this feature exists, but it's useful in some situations. For example, if you're using Webpack or some other packer or ES modules, variables delcared with var will not be stored in the global object and thus will not be accessible through other files. As such, if you want a variable to be available everywhere, you need to declare it directly via the global object (globalThis.varName = value).

Global Scope vs Global Object

As I noted above, variables declared inside ES modules will not be stored in the global object. You can think of the properties on the global object as variables on a "super-global" scope, above the global scope.

While the global scope includes all variables decalerd with var, let or const outside any functions in a file, the global object may or may not include all variables decalerd with var outside any functions in a file.

What ends up in the global object, the scope of the global object and how many global objects there are depends on the environment.

Upvotes: 1

Related Questions