I tested the following code:
(function(){
var x = false;
function x(){
return true;
}
return typeof x;
})();
It returns “boolean”. And only when I comment the second line:
(function(){
//var x = false;
function x(){
return true;
}
return typeof x;
})();
It returns “function”.
It means that if someone has declared a variable somewhere in the code before, my function declaration using the same name will fail, right? Please, someone explain it to me.
Thanks!
In JavaScript, function declarations are treated as if they were written first. Then variable declarations. (That particular ordering matters very rarely, if ever.)
In variable declarations, any assignment part is treated as a separate expression statement occurring at the point in the function where the
varstatement actually appears. Thus:is treated like:
Thus overall your first sample is treated as if it were:
Note also that functions and variables share a common namespace. A
vardeclaration without an assignment part for a variable name that’s already been declared has no effect. (At least, I think it has no meaningful effect, but JavaScript has weird dark corners …)