How does scope work in this javascript example?

I found a piece of code with which I had trouble understanding. If someone can take me through this, it would be nice. Here is 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 at main(), we will set a nameto bob. Then the function doSomethingcalls the anonymous function that we pass.

Now that I'm a little confused.

What is checking if (false)? If false, then reset ours nameto fred?

Then we move on to the warning name, which is good ... apparently undefined.

+4
source share

Source: https://habr.com/ru/post/1652900/


All Articles