简体   繁体   中英

Recursion in Javascript strange behavior

I'm struggling to find the answer to this question why does this code:

    (function h(){
        var x = 1;
        return x;
        x = 2;
    })();

Returns 1, when this code:

    (function g(){
        function g(){ return 1; }
        return g();
        function g(){ return 2; }
    })();

Returns 2

I've debugged it and in both cases in never goes past return g() or return x part. The recursion part in function g, should call function g() with the first implementation of it in which it returns 1.

This is because Javascript hoists (brings to the top) any function definition. The interpreter re-orders your outer function as:

(function g(){
    function g(){ return 1; }
    function g(){ return 2; }
    return g();
})();

The second g() overrides the first one, and so outer function returns the result of executing that second g(), which is 2.

More about hoisting can be found here

To get the result you were expecting, you can assign the functions as vars instead, this will not hoist them:

(function g(){
    var g = function(){ return 1; }
    return g();
    g = function(){ return 2; }
})()

That is called Hoisting :

Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

You should be careful with this and, by extension, with any magic that JS does when it tries to help you because you weren't disciplined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM