Node.js - Knowing the Global Objects

Subscribe to my newsletter and never miss my upcoming articles

By definition A Global object is,

An object that always exists in the global scope.

For web browsers, we have a window object. It provides the “browser window” functionality, and also play the role of a global object. In those web browsers, when scripts create global variables, they're created as members of the global object(window object). In Node.js, This is not the case.

Does Node.js has something called, global as web browsers got window ?

Oh, Yes. It does. Try this,

  • Create a file called, index.js
  • Copy following code into the file
  • Open a command prompt and type node index (I assume, you have Node.js installed and node is added to the classpath. Also note, I haven't provided the .js extension while executing the code. Node.js expects it to be a .js file by default.)

Do you see the output? It logs the entire global object like,

{ console: [Getter],
  global: [Circular],
   process {
     title: ' ',
     version: 'v8.11.1',
      [ 'Binding contextify',
        'Binding natives',
        'Binding config',
        'NativeModule events',
        'Binding async_wrap',
        'Binding icu',

As we know about the existence of global in Node.js, let us see what it provides and how it is different than browser's window object.

Try this code in your browser's Console,

var greet = 'Hello Thought Dump';

You should get the output that logs as, 'Hello Thought Dump'. Because the variable declared globally, would be accessible by the global object, i.e, window object.

Now copy-paste the following code in your index.js file,

var greet = 'Hello Thought Dump';

Save the changes and run from terminal as, node index. What do you expect to see? You will see difference in behavior for Node.js. It logs undefined. Why? Because, by creating a variable in Node.js file, you do not add that variable as a property to the global object.

Now modify index.js and try this code,

var greet = 'Hello Thought Dump';
console.log(greet); // no global.greet now

Running the above code will log 'Hello Thought Dump'.

Here are some facts:

  • In the Node.js module system, each file is treated as a separate module.
  • The Global objects are available in all modules.
  • While in browsers the global scope is the window object, in nodeJS the global scope of a module is the module itself, so when you define a variable in the global scope of your Node.js module, it will be local to this module.

Hope this explains the concept. There is much more to it, explore more on Node.js Global Objects.

Looking for interview questions that are essential in identifying the true masters of Node.JS development? This guide may help you!

No Comments Yet