I have taken some JavaScript courses lately (at codeschool) and, in one of them, they said:
- A function declaration (fd) builds in memory immediately when program loads;
- A function expression (fe) builds in memory dynamically during execution.
Thus fe has an advantage over fd which is saving some memory at loading time - I concluded.
So, for example, considering following two snipped codes below, there won't be any extra memory allocation on loading time because foo is going to be assigned to undefined thanks to hoisting.
// Original code
var foo = function (bar) {
console.log(bar);
};
Below we have code after hoisting
// Code after hoisting
var foo = undefined;
foo = function (bar) {
console.log(bar);
};
In shortness, foo is undefined and the function expression will only be assigned to foo once code runs. Thus it won't allocate extra memory on loading time.
Ok. No problems till now. However, "if fe has an advantage over fd which is saving some memory at loading time" following code should take some extra memory to be allocated at loading time since it's a function declaration.
function foo(bar) {
console.log(bar);
}
So the question is: is my reasoning right? If so, how much memory does it take at loading time and how is it calculated?