JS: DOM API
Theory: Global Window Object
In this lesson, we will learn about window. It is a global object provided by the browser.
It contains functions for opening tabs, controlling the position of the page, and various other things:
Windows are available in the DevTools console. Let's try calling the method from the example above there.
Here are some examples of its capabilities:
In addition, there's an object called document inside window. We can use in to work with the contents of the page in future lessons.
The window object sets the global execution context. The tag window stores all other globally accessible properties and objects inside itself. When we call global functions such as alert() or console.log(), the browser looks for them in the window object. In other words, we actually call window.alert().
The same applies to all other functions used directly and without imports:
The danger of the global state
The presence of the window object is a technical implementation from JavaScript, which should not be relied upon during development.
Let's observe this kind of code:
Setting a property in window automatically makes this property accessible from anywhere in the browser code. In other words, we have created a global variable.
Such variables cause a lot of problems during development. It's unclear where they come from and who changes them.
Global variables cannot be relied upon. There's a chance they might be modified by any part of the code, which often leads to errors in operation.
Moreover, on web pages, we can find various scripts which are not connected to each other. These can be various counters from analytical systems, marketing tools, and other such things. They all have access to the same window.
Because of it, we can end up in this situation: we set properties in window in one script and accidentally break the work of another script that uses the same global property.
If we want to achieve well-written code, we shouldn't directly encounter the window object. However, knowing about its existence is important for understanding how JavaScript functions in browsers.

