The global object

Javascript provides a unique global object accessible to all execution contexts. The global object has a number of properties predefined. Some of this properties are required by the ECMA standard and some are specific to the platform. See here the relevant documentation for Node.js and here for the HTML DOM.

How to access properties defined in the global object

Javascript provides two ways to access the properties in the global object:

  • explicit access
  • implicit access

Explicit access

Javascript platforms may include a global property whose value is the global object itself. In the HTML DOM, this property is window; in Node.js, the property is global property. This global property can be used to access properties in the global object from different execution contexts, for example:

In [1]:
(function() {
    global.myGlobalProperty = "Hello, World!";
})()
global.myGlobalProperty;
Out[1]:
'Hello, World!'

Implicit access

NaN and isNaN are properties defined in the global object. NaN is set to the "Not-a-Number" value defined by the IEEE 754 standard for floating-point numbers. And isNaN is set to a function that returns whether a number is NaN. Here is an example that illustrates how these properties are implicitly accessible from different execution contexts:

In [2]:
(function f() {
    return isNaN(NaN);
})()
Out[2]:
true

Note that although accessing global properties in this way is very convenient, it is also riddle with unexpected side effects:

In [3]:
(function() {
    var isNaN = function(number) {
        return !global.isNaN(number);
    };
    return isNaN(NaN);
})()
Out[3]:
false
In [4]:
(function() {
    isNaN = function(number) {
        return !global.isNaN(number);
    };
    return isNaN(NaN);
})()
TypeError: Cannot call method 'split' of undefined
    at formatError ([eval]:174:40)
    at sendError ([eval]:97:14)
    at onMessage ([eval]:74:13)
    at process.EventEmitter.emit (events.js:98:17)
    at handleMessage (child_process.js:318:10)
    at Pipe.channel.onread (child_process.js:345:11)