I have the following code, where I declare a function and after it, a variable with the same name as the function:
function a(x) {
return x * 2;
}
var a;
alert(a);
I expected this to alert undefined
, but if I run it, the alert will display the following:
function a(x) {
return x * 2
}
If I assign a value to the variable (like var a = 4
), the alert will display that value (4
), but without this change a
will be recognized as a function.
Why is this happening?
var a
you create a new variable. The declaration is actually hoisted to the start of the current scope (before the function definition). Afterwards the name is used up by the function of the same name. This is what you get when usingalert()
. – Rein