What is the global object in JavaScript? A practical guide for developers

Updated on March 14, 2024

·

Originally published on January 16, 2017

What is the global object in JavaScript? A practical guide for developers

The JavaScript global object and scope, and working with the variables and functions in it, are a key part of building apps with JavaScript.

Unfortunately, they are easy to misunderstand and misuse, leading to negative impacts on your applications’ functionality, performance, and security.

This post will explain the global object in JavaScript, covering scopes, variables, and functions, and how you should safely use the global context.

What is the global object in JavaScript?

The global object in JavaScript is available to all parts of your code. Any variables or functions inside the global object are in the global scope, which means you can use them in the functions, nested callbacks, and modules in your code — wherever they are.

Depending on your environment, the global object is accessible in different ways:

  • In the browser, the global object is accessed through the window variable.

  • In Node.js, the global object is accessed through the global variable.

  • In workers, the global object is accessed through the this variable. Note, however, that the global variable for each worker is isolated and separate to the global objects for the browser window and any other workers.

Due to this inconsistency, the globalThis variable has been introduced to standardize access to the global object regardless of which environment you are in. We’ll explain how to use globalThis to access the global object later in this article — but first, it’s important to understand why it was necessary.

The JavaScript global scope

The global object exists in the global scope. JavaScript scopes (also called contexts) determine where a variable or function that you have declared is accessible.

Map of JavaScript scopes

Each scope has access to the functions and variables declared in its parent scopes. There is a precedence to how JavaScript resolves variables that appear inside scopes: if variables of the same name have been declared in multiple scopes, JavaScript uses the first one it finds, starting at the current scope, and working up toward the global scope.

JavaScript scope

Description

Global scope

Variables and functions declared outside of a module, function, or block have global scope. 

Module scope

A module is a self-contained block of JavaScript code that can be exported and used by other modules in the same project. Variables and functions in the module scope are only available within that module.

Function scope

Variables and functions declared inside a function are only available within that function.

Block scope

A block of code in JavaScript is any code inside a set of matching curly braces {}. Variables declared inside a block using either let or const are only available within that block. However, if they are declared with var when not inside a function or when running in strict mode, they are accessible from outside the block.

You’ll also commonly see the term Local scope. This can refer to either the module scope or function scope and is usually used when discussing the current scope being worked in. A “local” variable means that variables declared within a module are local to that module, or variables declared within a function are local to that function.

When you should (and shouldn’t) use the global object

There are default functions and variables in the JavaScript global scope. In addition to these, specific environments will provide their own additional default objects:

All of the default global variables and functions are necessary for building apps on each platform, and are there to be used. However, when adding your own variables to the global scope, you need to be careful not to:

  • Declare a variable or function with the same name as an existing default variable.

  • Place sensitive information in the global scope in a way that could accidentally be leaked (for example, storing a user’s login details in a global variable in a Node.js app where they could be read by another user).

  • Re-use variable names in different scopes, which could lead to confusion if a function is unintentionally accessing a global variable instead of a local variable.

In web browsers, the global scope is usually heavily used: DOM elements like buttons, menus, and other interactive elements directly call global functions, and as a web page is a single-user environment, there are fewer concerns about declaring global variables that can be read application-wide.

In Node.js, the global object is usually used for storing data that needs to be accessed throughout an application, like API keys for third-party services or database credentials that need to be used in multiple functions. Environment variables, loaded from a file into the global process.env variable, are often used specifically for these purposes. To keep things clean, declaring reusable functions in modules is often preferred for organizing and accessing code in complex applications.

However, even when it’s safe to do so, over-relying on global variables has negative long-term consequences for the maintainability of your code:

  • Harder to debug code: When your variables can be modified from anywhere in your code, debugging becomes harder to follow.

  • Memory overconsumption: Each global variable remains in memory the entire time your page is loaded, so having too many of these will cause memory issues.

  • Namespace pollution: Having a very large number of global variables and functions can lead to naming conflicts.

The best practice is to use global variables and functions as strategically as possible, whether in the browser or in Node.js.

How to create and access global variables in JavaScript

Scope

Set a global variable from this scope

Access a global variable from this scope

Global
Declared variables and functions are automatically global


Browser: var myVariable = 'foo';

Node.js: var myVariable = 'foo';

Worker: var myVariable = 'foo';

Browser: console.log(myVariable)

Node.js: console.log(myVariable)

Worker: console.log(myVariable)

Function/local/block
Global variables/functions must be declared in the global object


Browser: window.myVariable  = 'foo';

Node.js: global.myVariable  = 'foo';

Worker: this.myVariable  = 'foo';

Browser: console.log(window.myVariable)

Node.js: console.log(global.myVariable)

Worker: console.log(this.myVariable)

Module
Each module has its own global scope, so global variables declared in one module will not be present in another

Within modules, global, function, and block scopes will behave the same way as they do in other environments. For example, functions inside modules will have their own function scope and must access the module’s global scope through window, global, or this.

How to create and access global functions in JavaScript

The process is the same for functions. If you are in the global scope, you can just declare a function and it will be accessible in the global object:

If you are not in the global scope, you need to specify where the function will be created:

Be aware that variable names and function names can conflict!

How to use globalThis to access the global object from anywhere

With multiple possible JavaScript environments (browser windows, Node.js, web workers) and multiple scopes in play, accessing the global scope in the above ways can be confusing and error prone. To combat this, the globalThis variable has been introduced, and is now supported in all major web browsers and in the latest versions of Node.js.

In JavaScript, the this variable refers to the current object. It was often used, when there was no current object, to gain access to the global object. This provides some consistency to accessing the global object in different environments, but it’s still confusing and this workaround fails if you’re inside an object. globalThis fixes this by returning the global object, no matter where you are.

Here’s how to use globalThis to set and access global variables and functions in browser windows, Node.js, and in workers:

globalThis calls this from the global scope, returning the global object, even when you’re not in the global scope.

This is much simpler than having a different behavior for different environments and scopes; however, it’s important to understand how to access the global object, and how scopes work without globalThis, if you want to be able to effectively write JavaScript code.

Reduce the amount of code you need to write by choosing the right tools

It’s nice to be able to brag about being a full-stack developer, but building and maintaining backend code can lead to small mistakes that lead to big problems — a simple variable mix-up in the JavaScript global object can lead to the loss of sensitive customer data and the consequences of that. 

By reducing the amount of code you write, you reduce the chance of show-stopping bugs appearing. For example, by integrating third-party authentication into your backends, you can ensure that your users’ information is being handled according to industry standards and avoid handling that sensitive information yourself. 

Similarly, using composable content platforms like Contentful means that you can skip building content delivery infrastructure and building backend interfaces for managing content and focus on making reliable, exciting user experiences.

Subscribe for updates

Build better digital experiences with Contentful updates direct to your inbox.

Related articles

What's TypeScript? It's a powerful tool for frontend & backend developers. It promotes better code quality and protects against common JavaScript mistakes.
Guides

What is TypeScript and why should you use it?

August 18, 2022

Next.js redirects are an important function for any frontend application. This tutorial demonstrates the four ways that you can create a page redirect in Next.js.
Guides

How to create a Next.js redirect in 4 ways (with examples)

September 20, 2024

Images are an effective means to express ideas or explain a concept.
Guides

Always look your best: WebP, source sets, and the Contentful Images API

September 20, 2022

Contentful Logo 2.5 Dark

Ready to start building?

Put everything you learned into action. Create and publish your content with Contentful — no credit card required.

Get started