Using Global Variables in Node.js

​Hey guys, in today's article I want to talk about global variables in Node. This article is aimed at developers who are at a beginner to intermediate skill level working with Node. If you have never heard of global variables or worked with them, no need to worry. This article will get you up and running in no time with everything you need to know about global variables.

What are Global Variables?

Global variables are very similar, if not identical, to regular variables. Global variables can be initialized with a value, that value can be changed, and they can even be cleared out like a regular variable. The difference between a regular variable and a global variable comes down to their scope. When you create a variable in a JavaScript file, that variables only exists in the scope that it was declared in. Now what do I mean by this? In the code below, you can see an example of two different variables with different scopes.

// Scope.js

let fileScope = "Can be accessed anywhere in the file";

function doSomething() {  
    let localScope = "Can only be accessed inside this function";
    fileScope = "Can be accessed in the function too!";
}

// This will result in an error because the variable does not exist
// outside the function.
localScope = "Try and change me here";  

In the code snippet above, we can see that there are two variables, fileScope and localScope. The variable fileScope can be changed or called from anywhere within this file, whereas the localScope variable only exists inside the function doSomething(). I'm sure at this point you are wondering what this has to do with global variables. When we talk about global variables, they exist for all of the files in a program meaning they have global scope for the program.

The reason this is possible is because JavaScript programs share a global namespace between all of the files in the program. To put it another way, imagine that your program is a giant file or container that has "imported" all the other JavaScript files. You then declare a variable in this large container file, that variable now has scope throughout the whole program. If you are not sure what a namespace is or you want to find out more about them, check out this article to learn more.

How to Declare and Use a Global Variable

Now that we have a better understanding of what a global variable in Node is, let's talk about how we actually set up and use a global variable. To set up a global variable, we need to create it on the global object. The global object is what gives us the scope of the entire project, rather than just the file (module) the variable was created in. In the code block below, we create a global variable called globalString and we give it a value. Next, we change the value of globalString, and then finally we set it to undefined.

// Global.js

global.globalString = "This can be accessed anywhere!";  
console.log(globalString); // Output: "This can be accessed anywhere!"

globalString = "Check me out now";  
console.log(globalString); // Output: "Check me out now"

globalString = undefined;  
console.log(globalString); // Output: undefined  
// Example.js

// We can use the global we created in Global.js in this file 
// as well.
console.log(globalString); // Output: undefined

globalString = “We can change it too!";  
console.log(globalString); // Output: "We can change it too!"  

What I have not talked about yet is another way that you can make a variable global. The reason I have excluded this is because it is not a proper way of setting up a variable. If you declare a variable in a file without using the keyword var and then assign a value to it, the global object will set a property for this variable. This process essentially turns it into a globally accessible variable. I strongly advise against using this method though as it is not the proper way to go about creating globals. It is also important to note that if you set the 'use strict' directive, Node will disable implicit globals and you will likely end up with an error at runtime rather than a working script.

Practical Use Cases for Global Variables

Now, you might be thinking to yourself that you want to go off and create global variables now that you know more about them. I am going to strongly caution against creating global variables for a few very important reasons.

The first reason is that when you create a global variable, it exists throughout the lifetime of the application. When a variable persists through the lifetime of the app it means that it is there, in memory, occupying resources while the app is running.

Second, using global variables can cause concurrency issues. If multiple threads can access the same variable and there are no access modifiers or failsafes in place, it can lead to some serious issues of two threads attempting to access and use the same variable. On the less severe end you may end up with a value you don't expect, on the more severe end, you could end up with a fatal crash.

The last reason I am going to talk about is that using globals can cause implicit coupling between files or variables. Coupling is not a good thing when it comes to writing great code. When writing code, we want to make sure that it is as modular and reusable as possible, while also making sure it is easy to use and understand. Coupling pieces of your code together can lead to some major headaches down the road when you are trying to debug why something isn't working.

If you want to know more about why globals are not recommended, you can check out this great article called Global Variables Are Bad.

If you feel confused as to the purpose of global variables, fear not. We are going to take a look at a few of the global variables that are built into Node and try to get a better understanding of why they are global and how they are used. In fact, you have probably used a few of them already without even realizing that they are global objects!

// Node Globals

console.log("Hello World!");

process.env.PORT = 3000;

setInterval({  
  console.log("2 seconds passed.");
}, 2000);

If you take a look at the above code block you will probably see at least one instance you have used before, console.log(). According the the Node documentation, the console object is a global that has a few methods allowing developers to do things such as printing a log or an error. Digging deeper into the docs we can see that console is really a global instance that is configured to write to process.stdout and process.stderr.

This brings us to the next statement that you see in the code block above, the process object. If you have put up a production build of a Node application, then you have likely had to set the port for the environment variable. The environment variable env is a part of the process object which is another global. You can access variables on the process object in any file in your project because it is global. If this object was not global, the console object would not be accessible from any file either, remember it is really an object that refers back to the process object.

setInterval is another function that you may have seen before if you ever had reason to delay an operation before executing it. setTimeout and setImmediate are similar in nature to setInterval and are both global functions as well. These three functions are a part of the timer module which exposes a global API allowing you to call these functions without requiring timer in your files explicitly.

​All of the above mentioned use cases are built in to Node and are global for a reason. The process object is global because it provides information about the current running Node process and therefore should be available from any file without having to require it. The same can be said of the timer module which contains a number of functions that are important and should be accessible anywhere without having to require it. If you would like to learn more about the existing global objects built into Node, I encourage you to visit the official documentation on Globals.

​I know that was quite a bit of information, so thank you for sticking it out. All of the above information was found in the documentation on Node's website. Please feel free to ask questions and give comments in the comment section below. Until next time guys!

Author image
About Sam Galizia
New York, NY Twitter Github
Sam is an iOS developer who loves working with Swift and is currently doing freelance iOS work. When not coding, he can be found playing video games on Steam or writing articles.