The global object provides variables and functions that are available anywhere. Mostly, the ones that are built into the language or the host environment.
In a browser it is named “window”, for Node.JS it is “global”, for other environments it may have another name.
For instance, we can call
alert as a method of
We can reference other built-in functions like
window.Array and create our own properties on it.
For historical reasons, in-browser
window object is a bit messed up.
It provides the “browser window” functionality, besides playing the role of a global object.
We can use
windowto access properties and methods, specific to the browser window:
varvariables and function declarations automatically become properties of
Please note, that doesn’t happen with more modern
Also, all scripts share the same global scope, so variables declared in one
<script>become visible in another ones:
And, a minor thing, but still: the value of
thisin the global scope is
Why was it made like this? At the time of the language creation, the idea to merge multiple aspects into a single
window object was to “make things simple”. But since then many things changed. Tiny scripts became big applications that require proper architecture.
Is it good that different scripts (possibly from different sources) see variables of each other?
No, it’s not, because it may lead to naming conflicts: the same variable name can be used in two scripts for different purposes, so they will conflict with each other.
As of now, the multi-purpose
window is considered a design mistake in the language.
If we set
type="module" attribute on a
<script> tag, then such script is considered a separate “module” with its own top-level scope (lexical environment), not interfering with
In a module,
var xdoes not become a property of
Two modules that do not see variables of each other:
And, the last minor thing, the top-level value of
thisin a module is
undefined(why should it be
<script type="module"> fixes the design flaw of the language by separating top-level scope from
We’ll cover more features of modules later, in the chapter Modules.
Using global variables is generally discouraged. There should be as few global variables as possible, but if we need to make something globally visible, we may want to put it into
Here we put the information about the current user into a global object, to be accessible from all other scripts:
We can test the global object for support of modern language features.
For instance, test if a build-in
Promiseobject exists (it doesn’t in really old browsers):
We can create “polyfills”: add functions that are not supported by the environment (say, an old browser), but exist in the modern standard.
…And of course, if we’re in a browser, using
window to access browser window features (not as a global object) is completely fine.