The global object in JavaScript: a matter of platforms, unreadable code and not breaking the internet

Global variables in JavaScript
January 16, 2017


When I started programming one of the first things that I learned was that I should avoid the usage of global variables whenever possible. It’s known as a bad practice in programming because it pollutes the global namespace and is not safe to work with. As a result, scripts may interfere with each other, which can lead to unexpected behavior and hard-to-find bugs.

Personally, I think there’s a finite number of situations where I’d consider placing something in the global object. So when I discovered a new TC39 proposal whose aim is to add a new global property to access the global object in Javascript, I was puzzled yet intrigued, and I had to look into it.

Sign up for your free Contentful account and start building in moments.

What is a global object in JavaScript?

The global object in JavaScript is an always defined object that provides variables and functions, and is available anywhere. In a web browser, the global object is the window object, while it is named global in Node.js. The global object can be accessed using the this operator in the global scope.

We’re not adding many variables to the global object anymore, are we?

Thinking of front-end code, it’s clear that additional global variables do have a strong use case. Libraries like jQuery place themselves in the global namespace to make their use as easy as possible by just adding a script element to an HTML page.

It’s common practice to use an IIFE (immediately invoked function expression) to prevent variables leaking into the global scope. This IIFE is then executed with the window object to set new properties on it.

For JavaScript code that is supposed to run only in one environment, there is nothing wrong with this approach. For the browser context we can simply pass window (or self or frames), and for the context of Node.js we can use global, but what about JavaScript that should work independently in any environment?

Universal JavaScript with Browserify

jQuery is clearly not a good example for JavaScript that runs everywhere, so let’s look at a different example. The testing framework Mocha runs in Node.js and the browser. A typical Mocha test file looks as follows:

To write a test in Mocha you have to use the describe and it function. The testing framework places these functions in the global object for you ready to use. The Mocha source code is initially written for the Node.js context which means that the accessible global object is global.

So what does it take to make this code runnable in the browser context, too?

Mocha uses Browserify to build an additional file that can run in the browser context. The build process wraps the code in an IIFE and provides an object named global.

For the sake of simplicity let’s look a simpler example that does nothing else than setting a foo variable to the global scope running in Node.js context.

After transforming this one line of “Node.js JavaScript” into “browser JavaScript” using browserify we get a rather cryptic result. When we look closer at it we’ll see that the code using the global object is now wrapped in IIFE which provides a global object as a function parameter. The function argument for this parameter is a heavily nested ternary operator checking for the presence of global properties.

I don’t know about you, but this is nothing I’d call beginner friendly or easy to read. Do we really need that many checks to figure out what the global object in an environment is?

Evaluating the global object is harder than expected

It turns out that there are even more angles to this problem. If we want to write JavaScript that uses the correct global object and can run in any environment, it becomes tricky, and many projects use different approaches to this problem.

So let’s look at the generated browserify output again.

This code looks one after another for the properties global, self and window to be present. If none of them is defined, it gives up and just assigns a new plain object. This evaluation covers the traditional browser environment, service and web workers and the Node.js context.

Pretty good — but trial and error doesn't feel right

This approach is neither maintainable nor very future proof and does not cover all the possibilities (yesterday I learned about d8 which is a JavaScript shell coming with V8 that does not include any of these global properties). We don’t know what the future brings and maybe there will be even more properties representing the global object. That means that our evaluation only becomes longer and longer, and uglier and uglier.

Isn’t this global?

I hear you say that this also refers to the global object (at least sometimes). So why can’t we go with an IIFE and passing this to it?

That’s right! This snippet works, but only if this snippet is not nested inside of another function. Because then this might refer to a changed context or even be undefined (code running in strict mode).

Relying on this is not a safe option to get the global object in JavaScript. And there is also to say, that ES6 modules will be available at some point and this at top level inside of a module won't reference the global object but rather be (thanks to Axel Rauschmayer for pointing that out).

So what other options do we have?

The function constructor can help!

Functions are an essential part of any programming language. In JavaScript, there are several ways to create them. The two common ones are function expressions and function declarations, but there is also the not so well known way of using a function constructor.

Functions that have been created using the function constructor always run in the global scope. This fact ensures that we’re dealing with the global scope and then using this becomes a safe way to retrieve the current global object.

This snippet works in strict mode, inside or outside of functions and is probably the best bet we have.

The big downside with the function constructor is that Content Security Policy directives will prevent its execution. CSP helps to reduce the risk of XSS attacks and is a useful technology, but unfortunately using function constructors falls into the category of “unsafe dynamic code evaluation”. So when we want to use function constructors we have to allow dynamic code evaluation and this is most likely something we don't want to do.

This chaos might be fixed soon

So in the end, it turns out that there is currently no silver bullet to retrieve the real global object in all possible environments. The function constructor is the most accurate one, but it’s not guaranteed that code using it won’t be blocked by CSP directives.

Daniel Ehrenberg had the same feeling and came up with a proposal to make the global object easily accessible to get rid of all these evaluations.

Everybody seemed to like this idea, and the proposal is currently on stage 3 of the TC39 process. One thing that may need further discussions is the actual name of the property that should hold the reference. Most people agreed with global similar to the Node.js environment.

At the time of writing, people are validating if this addition may have any negative impact on the web platform itself. Do you remember the drama about Array.prototype.contains? The web doesn’t forget code that was pushed out there. New language features have to be evaluated carefully to be sure that additions and changes are not breaking existing websites.

In fact, it turns out that adding the property global breaks Flickr and Jira, which probably means that the proposal has to be changed to use a different property name. Discussions about using self or started already.

So let’s hope for the best, because even when we try to avoid the usage of globals, there are use cases for them and these shouldn't need the usage of a heavily nested ternary operator that no one understands.

Links and resources

Show us what you've built: Contentful now has a Developer Showcase where devs from the Contentful community can share their projects with others. Join in!

About the author

Don't miss the latest

Get updates in your inbox
Discover new insights from the Contentful developer community each month.
add-circle arrow-right remove style-two-pin-marker subtract-circle remove