var a = function(){
alert("2");
}
function a(){
alert("1");
}
a();
As above, I declared two functions in different ways. When I run a()
, I got 2. Why?
When you declare a function or variable in JavaScript it gets "hoisted", meaning that the JavaScript interpreter pretends that the variable (a
in your case) was declared at the top of the file scope.
When that declaration takes the form function a() ...
, the definition of the function is hoisted along with the declaration.
Assignments like a = function ()...
don't get hoisted, and so that assignment happens after the function a() ...
piece and overrides it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With