Home > Article > Web Front-end > Function declarations take precedence over variable declarations in JavaScript
For the same identifier, declare it with var and function. What is it in the end?
var a; // Declare a variable with the identifier a
function a() { // Declare a function with the identifier a
}
alert(typeof a);
displays "function", that is, function has a higher priority than var.
Some people think this is the reason why the code is executed sequentially, that is, a is overwritten by the funcion executed later. Okay, swap them around.
function a() {
}
var a;
alert(typeof a);
The result still shows "function" instead of "undefined". That is, function declarations take precedence over variable declarations.
We slightly modify the code and assign a value at the same time when declaring a.
function a() {
}
var a = 1; // Note here
alert(typeof a);
At this time, "number" is displayed but not "function", which is equivalent to
function a( ) {
}
var a;
a = 1; // Note here that
alert(typeof a);
means "var a = 1" is split into two steps. a has been reassigned, naturally it is the last value.