skip to main content

Ryan Hettler

Resolve any Global Variable issues in JavaScript

March 12, 2015

End of June 2014, I went to Austin, Texas and met a couple of seasoned programmers. I spoke briefly with them about my experience with working with Javascript and PHP. Ilan Schnell – one of the programmers – wasn’t a big fan of PHP because of how it handled globals.

“The global namespace in PHP is littered with thousands of function names.” –  Ilan Schnell.

No wonder PHP is considered a better platform than a language. Ilan explained to be me that globals aren’t always bad; However, with that said, you would never want an important variable to be overwritten by another variable in another script or application. This can become arduous to test and debug. There is a technique to store variables into an object which will resolve any Global Variable issues in JavaScript.

For PHP’s sake, there are frameworks like Laravel that approach the PHP global namespace issue with it’s own implementation. Jeffrey Way and Taylor Otwell discuss in the podcast “Episode 21 – Commands, Pipelines and Packages” a testing platform called Behat which is able to run some “tests from the domain level” that Ruby on Rails Cucumber is not capable of doing. A huge step up for PHP.

A Single Global Variable to Contain the Variables

We start off with an single global variable which acts as a container for your program / application.

var AnotherPCGame = {};

This single global variable is where we can store our contained variables:

AnotherPCGame.LinisTheBosmer = {
   name : "Linis",
   alive : true
AnotherPCGame.ZirkanTheDunmer = {
   name : "Zirkan",
   alive : false
AnotherPCGame.HarikTheNord = {
   name : "Harik",
   alive : true

As demonstrated, we can reuse the same variables in different objects. Let’s say we need to retrieve the name variable from HarikTheNord. It can be retrieved by typing in:

Simple! Right?