Global object
What the global object is
The global object is a special object that always exists, regardless of the environment (browser, Node.js, and so on). It represents the global scope, where all global variables and functions live.
Simply put:
The global object is a "container" that holds all the variables and functions declared outside functions and modules.
Examples of global objects in different environments
| Environment | Global object |
|---|---|
| Browser | window or self |
| Web Worker | self |
| Node.js | global |
| Modern universal way | globalThis |
Example: browser
var x = 10;
console.log(window.x); // 10
console.log(this.x); // 10 (in the global scope)The variable x, declared with var, automatically becomes a property of the global object window.
Example: Node.js
var y = 5;
console.log(global.y); // undefinedIn Node.js, var, let, and const variables are not added to global, because Node.js uses a module system (each file is a separate module, not a global script).
The universal way: globalThis
ES2020 introduced a new standard, globalThis, which works the same way in every environment.
console.log(globalThis);It works:
- in the browser ->
window - in Node.js ->
global - in a web worker ->
self
Relationship to the execution context
When the global execution context is created, the JS engine:
- creates the global object;
- sets
thisas a reference to that object (unlessstrict modeis used); - places all global declarations (
var,function) into it.
Example:
var a = 42;
function sayHi() {
console.log("Hi");
}
console.log(globalThis.a); // 42
globalThis.sayHi(); // "Hi"The difference between let/const and var
Variables declared with let and const:
- do not become properties of the global object,
- but still exist in the global scope.
Example:
let a = 10;
var b = 20;
console.log(window.a); // undefined
console.log(window.b); // 20Summary
| Feature | Description |
|---|---|
| What it is | The top-level object that always exists |
| Where it lives | In the global execution context |
| Automatically contains | Global functions (setTimeout, fetch, console, ...) |
| How to access it | window (browser), global (Node.js), globalThis (universal) |
Specifics of let/const | They do not become properties of the global object |
Practical example using globalThis
globalThis.appName = "DemoApp";
function printName() {
console.log(globalThis.appName);
}
printName(); // "DemoApp"Works in the browser, in Node.js, and in any environment.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.