• Home

  • Custom Ecommerce
  • Application Development
  • Database Consulting
  • Cloud Hosting
  • Systems Integration
  • Legacy Business Systems
  • Security & Compliance
  • GIS

  • Expertise

  • About Us
  • Our Team
  • Clients
  • Blog
  • Careers

  • VisionPort

  • Contact
  • Our Blog

    Ongoing observations by End Point Dev people

    Preventing Global Variables in JavaScript

    Evan Tann

    By Evan Tann
    December 15, 2011

    JavaScript’s biggest problem is its dependence on global variables ―Douglas Crockford, JavaScript: The Good Parts

    Recently I built out support for affiliate management into LocateExpress.com’s Sinatra app using JavaScript and YUI.

    I used a working page from the admin, Service Providers, as a starting point to get something up and running for affiliates quickly. By the time I finished, the Affiliates page worked great, but forms on the Service Provider page no longer populated with data.

    Identifying a misbehaving global variable

    There were no errors in the console, and the forms on the Service Providers page remained broken even after restoring an old copy of service_providers.js. As it turns out, a global variable, edit_map, was defined within service_providers.js, and again in the copied affiliates.js. Credit for spotting the problem goes to Brian Miller.

    The fix was as simple as moving edit_map’s declaration into the file’s YUI sandbox, so that version of edit_map wouldn’t be visible to any other pages in the admin.

    Preventing global variables

    As projects grow and complexity increases, it becomes easier and easier to overlook global variables and thus run into this tough-to-debug problem. Douglas Crockford’s Javascript: The Good Parts covers several workarounds to using global variables.

    Rather than declaring variables globally, like this:

    var edit_map = { 'business[name]' : 'business_name' };
    

    the author recommends declaring them at the beginning of functions whenever possible:

    YUI().use("node", "io", "json",
    function(Y) {
        var edit_map = { 'business[name]' : 'business_name' };
        ...
    });
    

    In all other cases, he suggests using Global Abatement, which prevents your global variables from affecting other libraries. For example,

    var LocateExpress = {};
    LocateExpress.edit_map = { 'business[name]' : 'business_name' };
    
    YUI().use("node", "io", "json",
    function(Y) {
        ...
        return LocateExpress.edit_map;
    });
    

    I highly recommend JavaScript: The Good Parts to learn about the best JavaScript has to offer and workarounds for its ugly side. The author also wrote a very popular code-checker, JSLint, which could help debug this nasty problem by highlighting implicit global variables.

    javascript


    Comments