Skip to main content

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

EnvironmentGlobal object
Browserwindow or self
Web Workerself
Node.jsglobal
Modern universal wayglobalThis

Example: browser

javascript
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

javascript
var y = 5; console.log(global.y); // undefined

In 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.

javascript
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:

  1. creates the global object;
  2. sets this as a reference to that object (unless strict mode is used);
  3. places all global declarations (var, function) into it.

Example:

javascript
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:

javascript
let a = 10; var b = 20; console.log(window.a); // undefined console.log(window.b); // 20

Summary

FeatureDescription
What it isThe top-level object that always exists
Where it livesIn the global execution context
Automatically containsGlobal functions (setTimeout, fetch, console, ...)
How to access itwindow (browser), global (Node.js), globalThis (universal)
Specifics of let/constThey do not become properties of the global object

Practical example using globalThis

javascript
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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.