The Global object in JavaScript exposes useful variables & functions. It is known as the window in the browser & global in NodeJs. You can access the globalThis to access the global object irrespective of the environment in which JavaScript is run.
The JavaScript has a built-in object, which we call a global object which always exists in the Global Scope. The global object exposes useful variables and functions. It also exposes a variety of information about the environment in which code is running. Since it is part of the global scope, we can access it anywhere in the program
The global object has different names in different environments. For Example in a browser, the window object is the global object. In NodeJs call it global object
The window object is the global object in the Browser. It contains several useful methods & properties.
For Example, the alert method comes from the window object. You can invoke it as shown below.
window.alert("Hello")
You can also invoke it using shorthand. JavaScript automatically looks for it in the global object, which is the window object
alert("Hello")
Any variable we create using the var keyword in global scope is added to the global object by JavaScript. In the following example foo variable and window.foo points to the same variable.
var foo = "foo";
console.log(foo) //foo
console.log(window.foo) //foo
console.log(foo === window.foo); // Returns: true
Note that the let & const global variables do not become part of the global object.
let foo = "foo";
console.log(foo) //foo
console.log(window.foo) //undefined
console.log(foo === window.foo); // false
The alert, clearInterval, clearTimeout, setInterval, setTimeout & scrollTo are some of the functions that available in the window object
Node JS allows us to run JavaScript applications without using a browser. Even it has a global object and it goes by name global. The window object is not available under NodeJS.
The global object has different names in different environments. This creates a problem when we try to run the same JavaScript code in different environments. This is where globalThis property comes into the picture.
The globalThis is a global variable, which contains global this object. The global this object always points to the global object irrespective of whether the code runs in the browser, Node JS, or in any other JavaScript environment.
Hence we can always access the global object using the globalThis variable.
You can also use the global this object to access the global variable. But this will be undefined in Modules and inside functions running in strict mode.