The global object

JavaScript has a global object. It is, so to speak, the object of last resort. If there’s no other suitable object then JavaScript will use the global object (rather than reporting an error).


Douglas Crockford writes JavaScript’s global object ... is far and away the worst part of JavaScript’s many bad parts.

Getting global

Here’s how to get the global object.

js> return_this = function(){return this;}

function () {
    return this;

js> global = return_this()
[object global]

The programmer who wants to can always obtain access to the global object.

Global variables

Global variables are nothing more than attributes of the global object.

js> s = 'Hello world.'
Hello world.
js> global.s
Hello world.
js> global.i = 42
js> i

Global pollution

It’s very easy to inadvertently pollute (change) the global object. All it takes is an assignment to an undeclared variable in a function.

js> pollute = function(n){ i = n; };
function (n) {
    i = n;
js> i
js> pollute(13)
js> i

More global pollution

There’s a more subtle way to pollute the global object, which involves JavaScript’s this object.

To begin with, note that we can push values onto an array.

js> array = []

js> array.push(1, 2, 3)
js> array

Let’s try using array.push as a stand-alone function.

js> p = array.push
function push() { [native code for Array.push, arity=1] }

js> p(4, 5, 6)

The push function returns the length of the object it has just pushed to. So the value 3 above is a signal that all is not well. And indeed it is not. The original array is unchanged, and the global object has an entry at 0.

js> array
js> global[0]

It’s also got a length!

js> global.length


This behaviour is a consequence of What is this? and Bind is transient, together with JavaScript’s no-exceptions design.