I always thought that function a(){}
is identical to a = function(){};
However, these two snippets behave differently:
a();
function a() {
alert("Booya");
}
Prints Booya.
a();
a = function() {
alert("Booya");
}
Fails with an exception, which makes sense, since a is really not defined when called.
So - what kind of 'magic' lets the first snippet work, even though a()
is defined below its point of usage?
This is the difference between function declaration and function expression. This difference described well for example here.
In JavaScript all the declarations are hoisted. Means the variable can be used before it has been declared and function can be used before its declared. It’s JavaScript’s default behaviour to move all the declarations at top of the current script.
But this feature may lead to bugs in application so we use strict mode directive to avoid bugs. Strict mode does not allow to use variables without declaration.
more info at here
See this article for an explanation: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
Function declarations and variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter.
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