Is it possible to access variables within an anonymous function outside of said function?
No, and in fact this is one of the things we use functions for: Hiding things. :-) More below about why that's not just a quirk of syntax.
Variables within a function are entirely private to that function and other functions created within it (which "close over" the variables in scope where they're created). For instance:
function foo() {
var answer = 42;
function bar() {
var question = "Life, the Universe, and Everything";
console.log(question, answer); // Works fine
}
console.log(question, answer); // Fails with a ReferenceError because
// `question` is out of scope
}
foo();
bar can access foo's answer variable because bar is created within foo. But foo cannot access bar's question variable because foo isn't created within bar.
This means it's possible to create functions that can access and modify a private variable:
// This is ES5 and earlier style; in ES2015+, it could be a bit more concise
function foo() {
var answer = 42;
return {
getAnswer: function() {
return answer;
},
setAnswer: function(value) {
answer = value;
}
};
}
var o = foo();
console.log(o.getAnswer()); // 42
o.setAnswer(67);
console.log(o.getAnswer()); // 67
Note that if we tried to replace
console.log(o.getAnswer()); // 42
with
console.log(answer);
there are two good reasons that fails:
The variable is out of scope
If somehow it were in scope, which answer should it refer to? We can call foo more than once, and each call creates a new answer variable, so...
Side note: It makes no difference whether the function is named or anonymous, or whether it's a normal function or one of ES2015's new "arrow" functions.