1

I was practicing some scenario and find a case:

Here is fiddle

According to closure bar function should have access to var x so I expected to alert 1 and condition get false due to if(!1) but it alerted undefined and condition get true and second alert is with value 10.

var x = 1;
function bar() {
    alert(x);
    if (!x) {
        var x = 10;
    }
    alert(x);
}
bar();

So I am confused why it is prompting undefined?

According to hoisting in a particular scope you define a variable anywhere it is considered as defined at top always.

If it is due to hoisting effect it still have to alert 10 instead of undefined.

2 Answers 2

5

Hoisting causes a variable to be declared everywhere in the function, not defined.

On the first line of bar, since there is var x on line 3 of the function, the global x is masked and you see the local x (which is undefined since it hasn't been given a value yet).

On line 3 of bar, you have x = 10 which defines the variable. This is not hoisted.

On line 5, you alert it, and it is now defined.

Venn Diagram of the above

Sign up to request clarification or add additional context in comments.

Comments

1

Hoisting will make your code effectively work like this:

var x;
x = 1;
function bar() {
    var x; //same as var x = undefined;
    alert(x);
    if (!x) {
        x = 10;
    }
    alert(x);
}
bar();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.