JavaScript variable scoping -- keeping the global clean

Discussion in 'Web Design and Development' started by congay, Oct 23, 2014.

  1. congay Suspended

    Sep 16, 2014
    Those of us familiar with javascript know we should not be polluting the global scope with variables, I'm just wondering what the best method is as I use quite a few in various places, all seem to work but I'd be interested to know what others think is the better method.

    1. Using an object with the function as a method.

    var scope1 = {
    init: function(){
    // Variables here are only scoped to this objects init method

    2. using a declared function

    function scope2(){
    // variables here are scoped to this function only

    3. using an immediatley invoked function expression (IFEE)

    (function scope3() {
    // variables here closed to this function scope.
  2. NeilHD macrumors regular

    Jul 24, 2014
    You're certainly correct in wanting to reduce the number of global variables you use.

    The bigger question though is why do you have so many? Always try and limit the scope of variables to the smallest possible. Only need it in one function? Define it in the function. Only need it in a loop? Define it in a loop. If you have loads of global variables your design may need looking at! Apologies if I'm teaching you to suck eggs here!

    We tend to organise our JS into namespaces, so the only truly global thing is the top level of the namespace. Nothing gets put into truly global scope apart from that (with the exception of some Google Analytics bits and some performance tracking bits). Then other namespaces are defined within that, to narrow things down a bit. So we might have something like:

    var tln = {};

    $.extend(tln, {
    Accounts: {},
    UI: {},
    Page: {}

    tln.CurrencyCode = "USD";
    tln.Accounts.Username = "neilhd";

    and so on.

Share This Page