Variable hoisting and function overwrite

Viewed 55

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?

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.

Related