Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intentionally "freezing" a javascript variable using a self-executing function

Tags:

javascript

I was reading a blog post here about creating a scraper with node.js and came across an interesting bit of javascript that I can't quite wrap my head around. This is the exact sort of thing I would like to use in my scripts, but as a bit of a newbie I don't want to blindly copy and paste code without knowing exactly what they do first.

In this function:

function main()
{
    var a = 1;
    var f = function() { console.log(a); }
    a = 2;
    f();
}
main();

the output is 2, because var a is changed before f() is called.

However, in this function

function main()
{
    var a = 1;
    var f = ( function(a) { return function() { console.log(a); } } )(a);
    a = 2;
    f();
}
main();

the output is 1. There is a fairly detailed explanation of this in the blog post linked above, but I can't for the life of me work out exactly why this works.

The post mentions the scope of var a being passed into the function - can anyone elaborate on what this means? And why is it necessary to have the final (a) at the end of the var f function?

like image 885
JVG Avatar asked Apr 20 '26 23:04

JVG


1 Answers

Maybe you can understand it if it is written as follow

function main()
{
    var a = 1;
    var f = ( function(b) { return function() { console.log(b); } } )(a);
    a = 2;
    f();
}
main();

This is called variable shadowing - by naming the parameter of the function with the same name we are hiding it from the function scope. If we do not shadow the variable, as in my example, the code is straighforward - we are defining function (1) that returns function (2), the returned function upon execution prints the value passed to function (1). we are passing the current value of a to the function, so the resulting code is

var f = ( function(b) { return function() { console.log(b); } } )(1);

or

var f = function() { console.log(1); }
like image 171
Maxim Krizhanovsky Avatar answered Apr 22 '26 13:04

Maxim Krizhanovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!