function setupSomeGlobals() {
// Local variable that ends up within closure
var num = 666;
// Store some references to functions as global variables
var gAlertNumber = function() { console.log(num); }
}
setupSomeGlobals();
gAlertNumber(); //works, WHY?!!
console.log(num); //does not work, GOOD
I expected gAlertNumber() to not work outside the setupSomeGlobals() function…
Variables declared with
varare always going to be local and won’t be accessible from the outside.If you run this in the console, it is more likely that you might have polluted the global namespace through earlier tries. Open a new tab and run the code again.