I found a snippet of code that I am having trouble understanding. If someone can take me through it, it would be nice. Heres the code, I will add my attempt below
main()
function main()
{
var name = "bob";
doSomething(function()
{
if (false)
{
var name = "fred";
}
// Were you expecting it to be "bob"?!
alert(name);
});
}
function doSomething(callbackFunction)
{
callbackFunction();
}
OUTPUT
undefined
My attempt
First within main()
, we set a name
to bob
. Then the function doSomething
calls the anonymous function we pass in.
Now heres where I get a bit confused.
What does if (false)
check? If what is false, do we reset our name
to fred?
We then proceed to alert the name
, which well... is apparently undefined
.