Function Declarations vs Function Expressions:
On the Home page of this site, we mentioned briefly about these. Let's try to understand them better here:
- Function declarations:
- Function expressions:
Within the code to this website I have been using these, except for self declaring functions: these are function expressions.
More on them below. Function declarations do not require variable assignments. Thus, they must start with the word function
and must be named.
These require variable assignment. Thus, let name = function()
where name
is the variable and function()
is what has been assigned to the variable called name
. The function itself can be anonymous, as in the case above, or it can be named:
So why is a self declaring function a function expression? Because they declare themselves. Effectively, a self declaring function is saying:
"I'm calling myself" - it has given itself a name, that of "self declare".
It is for this reason that a self declaring function
is written within brackets and has further brackets after itself:
So what is the difference betxeen the two functions?
Hoisting.
When JavaScript loads, it hoists to the top of the page - it is read first in other words. As JavaScript retains the last instruction, it effectively runs the last piece of code.
Result of function foo():
Above, we said that the keyword return
causes the code to break, to stop running. Within the function foo()
we
have a return
. However, due to hoisting, JavaScript
has ignored the first call of the function, and thus overridden the return.
Thus, our reult is 8 instead of 3.
Contrast this with a function expression:
Result of function foob():
Variable declarations (var obar
) get hoisted, but their assignments do not. Thus, the code
is reading:
var obar = undefined;
var obar = undefined;
which means that as the code is looking out for an instance of var obar
, the first function obar()
is returned, and then the code
breaks.
The same is true in the follwoing instance:
Result of function fooba():
While with the follwing, nothing is returned as the code is told to return;
a variable that has been declared but not assigned
until after the code has stopped:
Result of function foobar():
Read more about function expressions here.