stackjlei
stackjlei

Reputation: 10035

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);

Upvotes: 1

Views: 57

Answers (1)

Christos
Christos

Reputation: 53958

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 then 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, as I can infer from your code. So if you hand't defined this function, the the second step I mentioned before would have been done and since there is variable called a, would had alter it's value. If there isn't there any variable then a would have been defined on the global scope and it's value would have been 10.

var a = 1;
function b() {
    a = 10;
    return;
    // I renamed the function from a to c to notice the hoisting
    function c() {}
}
b();
console.log(a); 

Upvotes: 4

Related Questions