# Version A - Function Declaration Statement
// Some JavaScript code
function a() {
// code within function
}
//Some more JavaScript code
# Version B - Function Expression
// Some JavaScript code
var b = function () {
// code within function
};
// Some more JavaScript code
I've been reading JavaScript: The Definitive Guide and I wanted to make sure I'm understanding how these 2 versions are being processed by JavaScript. I'll explain my understanding for each version below:
Version A
- JavaScript scans the script at the global scope and identifies all variable and function definitions and hoists them to the top. Variable assignments and function evaluations won't happen yet.
- For the function a(), JavaScript will then package up the global context and associate it with the scope chain of the function. At this point, the function a() will know all the variable and function definitions in Step 1.
- JavaScript does NOT evaluate the function a() and therefore doesn't know anything about the local context within the function. This will remain true until the function is invoked.
Version B
Same as step 1 from above - JavaScript scans the script at the global scope and identifies all variable and function definitions and hoists them to the top. Because the variable b is hoisted to the top, the script is equivalent to this:
var b; // Some JavaScript code b = function (){ /* code within function */ }; // Some more JavaScript code
When JavaScript comes to variable b's assignment, it sees that an anonymous function object is being defined. When JavaScript defines the function, it will package up the context in which the function is defined (in this case, it's the global context) and associate it with the scope chain of the function. At this point, the anonymous function will know all the variable and function definitions in Step 1 which includes var b being undefined.
- Because JavaScript sees that the function is being used as an expression in a variable assignment, it will evaluate the function expression. When it evaluates the function expression, it will again hoist all variable and function definitions within the local scope to the top and if there are any function declaration statements within this function expression, it'll package this local context and add it to the scope chain of this function.
- A function object is returned when the function is evaluated and then the function object is assigned to var b.
If you could comment on each of the versions and let me know if my understanding is accurate, that'd be great.