2

This closure code would work:

function setupSomeGlobals(){
    var num = 666;
    gPrintNumber = function() { // play with var assignment 
        console.log(num)    
    }
    gIncreaseNumber = function() {
        num++;
    }
}

setupSomeGlobals();

gPrintNumber();
gIncreaseNumber();
gPrintNumber();

Yet, when I place the var keyword in front of the functions within the code, it all seems to not work. Why is that? Is var making these variable local only? Why would that matter?

function setupSomeGlobals(){
    var num = 666;
    var gPrintNumber = function() { // play with var assignment 
        console.log(num)    
    }
    var gIncreaseNumber = function() {
        num++;
    }
}

setupSomeGlobals();

gPrintNumber();  // ReferenceError: gPrintNumber is not defined
gIncreaseNumber(); 
gPrintNumber();
ApathyBear
  • 9,057
  • 14
  • 56
  • 90

1 Answers1

1

Is var making these variable local only?

Exactly. You can't access local variables from outside the setupSomeGlobals function.

Undeclared variables, i.e. without var, become global variables, which you should avoid as very bad practice. If you want to encapsulate some functions in a clean and safe way, try module pattern:

function setupSomeMethods() {
    var num = 666;
    return {
        gPrintNumber: function() {
            console.log(num)    
        },
        gIncreaseNumber: function() {
            num++;
        }
    };
}

var methods = setupSomeMethods();

methods.gPrintNumber();  // 666
methods.gIncreaseNumber(); 
methods.gPrintNumber();  // 667
dfsq
  • 191,768
  • 25
  • 236
  • 258