If you want to fix the issue, simply remove the a
parameter from the closure:
function test(a) {
return function() {
// ^^
console.log('a is : ' + a);
}();
}
There are much better explanations available than this, but I'll give it a go: test
is returning a function (closure) that "captures" the environment (or scope) in which it lives, including all variables, and takes them with it. Because you were passing in an argument to that function, the console.log was expecting it. But because it was an immediately-invoked function, you either needed to pass in a
to the function (like Aravinder shows in his/her answer), or don't, and just allow the closure to use a
that was "passed to it" from the parent function.
Hope that was helpful.
To be fair, that's not a pattern you usually come across (or, at least, I don't). You're more likely to see something like this. Here bob
is a function that contains a
because a
was returned along with the closure when test
was called.
function test(a) {
return function() {
console.log('a is : ' + a);
};
}
var bob = test('A should not be undefined?');
bob();