byteBiter byteBiter - 3 years ago 325
Javascript Question

Javascript hoisting

I am learning

javascript
hoisting feature, and find the following codes are really confusing:

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


The output is
1
. As far as I know, because of
hoisting
, the codes above are equivalent to

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


What happens when a
function
and a
variable
has the same name
a
?

Answer Source

What happens when a function and a variable has the same name a?

Nothing special. One assignment to a overwrites the other because they are both values.

console.log(a) // a points to a function here
var a = 4
console.log(a) // a points to 4 here
function a() {}
console.log(a) // a also points to 4 here!

By the way, a variable in a scope outside of a function can only be modified by that function if the variable isn't local to the function.

var a = 4
;(function() {
    a = 5
})() // <-- Immediately calling the function here
console.log(a) // a is now 5
;(function() {
    a = 6
    var a
})()
// a is still 5 because in the previous function,
// a was local to the function's scope
console.log(a)

Function parameters are implicitly local to the variable, so they automatically "shadow" globals that share the same name.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download