I'm referencing this link about closures: https://stackoverflow.com/questions/111102/how-do-javascript-closures-work

This is specifically about javascript. In the second answer with 956 votes, The author returns the nested function "sayAlert" after assigning it to the var keyword as shown below. (Example 3)

function say667() {
// Local variable that ends up within closure
var num = 666;
var sayAlert = function() { alert(num); }
return sayAlert;
var sayNumber = say667();
sayNumber(); // alerts 667

However in the next example (Example 4), the author assigns the following functions, "gAlertNumber", "gIncreaseNumber", and "gSetNumber", without the var keyword. Then the author is able to call the nested functions as follows.

function setupSomeGlobals() {
// Local variable that ends up within closure
var num = 666;
// Store some references to functions as global variables
gAlertNumber = function() { alert(num); }
gIncreaseNumber = function() { num++; }
gSetNumber = function(x) { num = x; }

gAlertNumber(); // 667
gAlertNumber(); // 5

var oldAlert = gAlertNumber;

gAlertNumber(); // 666

oldAlert() // 5

I tried adding the keyword var to the begging of each nested function, but in my console it returns an error. So I'm assuming there's a difference between the two. But I don't know what this tactic is called and why it works...


This is not just for functions - this is how JavaScript generally deals with assignments. When you use the var keyword, the variable is assigned at the current scope. When you don't use it, the variable is assigned at the global scope(the window object in browsers). That means that gSetNumber = ... is the same as window.gSetNumber = ...(assuming the code is ran in a browser) and gSetNumber(5); is the same as window.gSetNumber(5);. Since the window object is accessible from anywhere so is gSetNumber. sayAlert, on the other hand, was declared with the var keyword so it belongs to the local scope where it is declared and only accessible from there.

Note that while num is also a local variable declared with the var keyword, gAlertNumber, gIncreaseNumber and gSetNumber can be used to indirectly access it from anywhere since their closure closes over the local scope where num is declared but the function themselves are assigned to global variables.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.