Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the output of this JavaScript function is 10? [duplicate]

Tags:

javascript

Check this fiddle or the below code and tell me why is the output of this script is 10

var foo = 1;
function bar() {
    if (!foo) {
        var foo = 10;
    }
    alert(foo);
}
bar();
like image 304
SharpCoder Avatar asked Dec 16 '25 15:12

SharpCoder


1 Answers

Because the var in the function, hoists the variable up to the top. As if you declared it at the top of the function, and so foo is treated as a local variable in the current scope, the foo in the global scope is not affected. Your code is the same as this:

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

As you can see, foo is declared at the top of the function and is undefined, but importantly doesn't get a value until inside the if statement.

like image 74
MrCode Avatar answered Dec 19 '25 11:12

MrCode



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!