Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, declare the variable inside a function, why function gets the higher priority? [duplicate]

Tags:

javascript

    function bar() {
        return foo;
        foo = 10;
        function foo() {}
        var foo = 11;
    }
    console.log(typeof bar());

typeof bar returns function?! why not number?

like image 506
Weijing Lin Avatar asked Feb 24 '17 06:02

Weijing Lin


2 Answers

JS functions are executed in two passes three passes. First, the engine walks through the code, looks for function declarations and hoists them (=moves them to the top), second, it hoists variable declarations (unless the same name is already hoisted), finally it runs the "normalized" code.

In your snippet, the engine picks function foo and moves it to the top of the function. The subsequent var foo is ignored.

This results in the following "normalized" code:

function bar() {
    function foo() {} 
    return foo;
    foo = 10;
    foo = 11;
}

which explains your results.

Reference: Declaration Binding Instantiation, notice steps 5 and 8.

like image 65
georg Avatar answered Oct 13 '22 15:10

georg


return foo just references to function foo() {} so it's returning Function

function bar() {
    return foo; // function foo() {} 
    foo = 10; 
    function foo() {}
    var foo = 11;
}
alert(typeof bar()); // function

another scenario

function bar() {
    return foo;  // returns foo undefined as no value is assigned       
    foo = 10;           
    var foo = function () {}   // referenced to variable
    var foo = 11;       
}

alert(typeof bar()) // undefined 

here it will return number

function bar() {
    foo = 10; 
    return foo; // 10
    function foo() {}
    var foo = 11;
}
alert(typeof bar()); // number 10

this too will return a closure function which returns a number

function bar() {
    foo = 10;
    return function () {
      return foo 
    }
    var foo = 11;
}
alert(typeof bar()()); // number 10
like image 21
Parwat Kunwar Avatar answered Oct 13 '22 15:10

Parwat Kunwar