Khaino
Khaino

Reputation: 4159

Why function expression is called when there are function declaration and function expression with same name?

Here I have two function declarations with same name.

function a() {
    console.log('a1')
}
function a() {
    console.log('a2')
}
a();

It make senses that a() prints a2.

And here are a function declarations and a function expression.

b = function() {
    console.log('b1')
}
function b() {
    console.log('b2')
}

b();

But here b() prints b1, what is the reason?

Upvotes: 2

Views: 60

Answers (2)

Mahdi
Mahdi

Reputation: 216

I think this is the cause of hoisting. because hoisting moves all declarations to the top of the current scope (to the top of the current script or the current function). and here the function assign to **b for hoisting.**

Upvotes: 1

Travis J
Travis J

Reputation: 82297

function b() will hoist the definition to the top of the containing scope. As a result, it is declared first. Following that, b is then assigned to with your b = function assignment, and when you call b() it then logs 'b1'.

Upvotes: 4

Related Questions