stackjlei stackjlei - 1 month ago 7
Javascript Question

How does an empty function declaration work with hoisting in javascript?

Looking at the hoisting example from this site, I don't get why the below alters 1 even after the hoisting:

var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a); // alerts 1


is actually

var a = 1;
function b() {
function a() {}
a = 10;
return;
}
b();
alert(a);


Shouldn't it alter 10 because
a
is still assigned to 10 before
b
function returns? Why does calling an empty a function cause this? On a related note, why does the below not alert function but still alter 1? Doesn't
a
get reassigned to a function with the declaration?

var a = 1;
function a() {}
alert(a);

Answer

Let's take it line by line,

Here, b(); you call the function b. What has the function b in its body? The declaration of a new function whose name is a. When you access a inside the b, you actually don't access the global variable a, but the function you just declared. So the 10 will be set to the pointer that points to function called a and not the global variable called a

But why does the first block of code alerts 1? I am confused

Because when the JavaScript engine goes to execute the assignment:

 a = 10;

checks where a has been defined. Since in the current scope, where you try to set 10 to a, there is a function declaration, whose name is a, Then will happen that I described above. But you would say why? The function declaration is below the assignment. The reason why this is happening is the fact the JavaScript engine first process the declarations in your script and the proceeds to the execution of your script. So when the engine would questioned about a, where a is defined, as always it will look first at the current scope. If there isn't there then it will look in the scope where the current scope is enclosed. In your case this is the global scope.