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?
You should also remember that
var a
is hoisted, which makes it more like thisRemember that
var a
is hoisted, so if you assign4 to a
:If you use a function name as variable name, its value is replaced by function body. So "var a" becomes your function "a" body and thus your alert displays function "a".
In JavaScript both function declaration and variable declarations are hoisted to the top of the function, if defined in a function, or the top of the global context, if outside a function. And function declaration takes precedence over variable declarations (but not over variable assignment).
Function Declaration Overrides Variable Declaration When Hoisted
First you declare a variable:
Second, the value of
a
is a function because function declaration takes precedence over variable declarations (but not over variable assignment):And that is what you get when you call
alert(a);
.But, if instead of declaring a variable you make variable assignment:
var a = 4;
then the assigned value4
will prevail.ES6 comes with a better solution by defining
SyntaxError: Identifier (?) has already been declared
when usinglet
/const
instead ofvar
.let
const
Note that
const foo;
does not work. It will causeSyntaxError: Missing initializer in const declaration
Functions are a type of object which are a type of value.
Values can be stored in variables (and properties, and passed as arguments to functions, etc).
A function declaration:
A
var
statement:Both your declaration and
var
statement are hoisted. Only one of them assigns a value to the variablea
.