Mark Thomas Miller

JavaScript global variable avoidance

Let’s say you’re writing frontend code for an eCommerce store. You’re a beginner JavaScript developer, so you use a vague little variable called pX to calculate the price of an item plus shipping.

However, you notice something peculiar: one of your products, a simple toothbrush, is listed as $3.89 without shipping and a whopping twenty four million dollars with shipping.

You’re not an expert in toothbrush transit, but you think this might be a mistake.

It just so happens that pX, your price-with-shipping variable, was also used by that weird little snippet you inserted to make the product image magnify on rollover. pX was being multiplied to magnificent proportions and then called on to display the price.

Your site now holds the record for World’s Most Expensive Toothbrush… and it’s also a victim to global variables.

How do you stop this from happening?


Using object literals to limit usage of the global namespace

When I first started out with JavaScript, I thought that many explanations of how to conceal global variables were a little bit too advanced for my projects. I didn’t want to, say, buy an entire coffee company just to have a cup of coffee in the morning. I wanted something simpler.

For your current projects, you probably just need a way to be a good citizen of the global namespace: you don’t want your code to unexpectedly smash into other peoples’ code when it’s running.

In this case, you can limit your exposure to the global scope by keeping variables contained inside of an object, which is a fancy way of saying “a container that holds data”.

To do this, we’re going to take advantage of object literals.

// Create an object literal.
var house = {
    windows: 10, 
    roof: "Tesla solar tiles", 
    walls: 4
};

// Dot notation calls variables (example only)
alert(house.windows); // 10

You can also contain functions and even other object literals inside of an object literal:

var house = {
    windows: 10,
    roof: "Tesla solar tiles",
    garage: true,
    // Add functions
    lightsOn: function(room) {
        ...
    },
    // Add another object literal
    owner: {
        name: 'Mark Miller',
        occupation: 'Sorcerer',
        coolness: 7 
    }
};

There are a few advantages to using object literals: they’re succinct, easy-to-read, and they allow you to employ an elegant “key: value” structure in your code. If I wanted to find out how many windows were on the house, I could just call house.windows – easy, right? However, there’s still a chance that somebody else could call house and overwrite it. Also, this code could turn into a syntactic nightmare if the project was slightly longer.

To fix this, let’s add some safety and modularity to the code:

// If 'house' exists, keep it the same.
// If it doesn't, create an empty object.
var house = house || {};

// Now you can add properties to 'house'.
house.owner = {
    name: "Mark Miller",
    occupation: "Sorcerer",
    coolness: 7
};

house.config = {
    roof: "Tesla solar tiles",
    bedrooms: 3,
    bathrooms: 3,
    garage: true
};

For a great explanation of the benefits of this method, read this.

For small-to-medium JavaScript projects, I think that going much further than this would be a case of “buying the coffee company to have a cup of coffee”. If you just need a way to write an easy and extensible structure to shield against creating too many global variables, this method should be able to cover you.