Javascript Function Processing Order

Can someone explain in detail why in the next function the return value is 1.5? Does javascript develop bottom or top or more?

    (function f() {
        function f() { return 1; }
        return f();
        function f() { return 2; }
        function f() { return 1.5; }
    })();
+4
source share
3 answers

Functions: hoisted 'at the top of the area in which they live.

So your code really reads:

(function f() {
    function f() { return 1; }
    function f() { return 2; }
    function f() { return 1.5; }
    return f();
})();

QED:

(function f() {
    function f() { return 1; }
    return f();
    function f() { return 1.5; }
    function f() { return 2; }
})(); //=> 2
+4
source

jsFiddle Demo

As a result of the rise, this is equivalent

(function f(){
 var f;
 f = function(){ return 1; };
 f = function(){ return 2; };
 f = function(){ return 1.5; };
 return f();
})();

Climbing can be difficult because there are two aspects. First, the definition of a variable goes up

, . 1

,

( vars). vars , , op-ops, . 1

1: Scope Cheatsheet MDN

+1

js interprer , var ( ) , , . f, 1.5, , 2 f functios

+1
source

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


All Articles