While browsing through a blog post here that discusses creating a web scraper using node.js
, I stumbled upon an intriguing piece of javascript that has left me somewhat perplexed. This particular snippet of code seems like something I could implement in my own scripts, but as a newcomer, I want to understand its functionality before blindly incorporating it.
Take a look at this function:
function main()
{
var a = 1;
var f = function() { console.log(a); }
a = 2;
f();
}
main();
In the above code, the output is 2
because var a
is updated before calling f()
.
On the other hand, consider this function:
function main()
{
var a = 1;
var f = ( function(a) { return function() { console.log(a); } } )(a);
a = 2;
f();
}
main();
In this case, the output is 1
. The blog post linked earlier provides a detailed explanation, but I'm still struggling to grasp the concept completely.
The blog mentions something about the scope of var a
being passed into the function – can someone shed more light on this? Furthermore, why is it necessary to include the final (a)
at the end of the var f
function?