Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable hoisting and function overwrite

Tags:

javascript

I'm trying to understand the example below:

(function (){ 
    var func = function(){
        console.log('foo')
    }
    function func(){
        console.log('bar')
    }
    func();
})();

Why does this prints foo and not bar? Does it has something to do with variable hoisting?

I'm also confused by the code below:

(function (){
    function func(){
        console.log('bar')
    }
    var func = function(){
        console.log('foo')
    }
    func();
})();

My logic says, that JavaScript will execute the first function it sees, but the output shows something else. Why this still produces the same output as the first example? Am I missing something?

like image 784
Wahalez Avatar asked Sep 11 '26 17:09

Wahalez


1 Answers

Function declarations are hoisted. Assignments are not.

In the first case, the declaration is hoisted and then overwritten by the assignment.

In the second case, the declaration is the first thing in the function (so hoisting makes no difference) and then still overwritten by the assignment.

like image 101
Quentin Avatar answered Sep 14 '26 06:09

Quentin



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!