PHP-style $GLOBALS in Javascript?

March 8th, 2008. Tagged: JavaScript

Javascript has implied globals. When you skip the var in var a = 1; and go a = 1;, then a becomes a global variable. Some consider this an error in the language. Global variables should be avoided because they tend to overwrite each other in unexpected places, especially if the project grows in LOC and number of developers.

In PHP on the other hand, variables are local. If you need a global variable, then you have to have to be explicit about it using the $GLOBALS superglobal array.

So how about this: adopt the $GLOBALS convention in your JavaScripts? At the top of the script you go:

$GLOBALS = {};

Then every time you need a global variable, you do:

$GLOBALS['myglob'] = 1; // very PHP-like

or if you prefer:

$GLOBALS.myglob = 1;

Benefits of the approach:

  • global variables easy to spot (even from an aeroplane)
  • if it's not $GLOBAL, it's meant to be local. If it's missing the var, it's an error

Drawback:

  • It's a convention, so it can only help, but not enforce any coding practices

How many globals

Here's a quick test to check how many globals you have in a page.

(function(){
  var globs = 0;
  for (var i in window){
    globs++;
  }
  alert(globs);
})()

Run this script in your page without the scripts. Then add the scripts to the page run again. The result should be only one more global var if you followed the $GLOBALS convention.

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov