First, memory is set aside for all necessary variables and declared functions.
// How a function is built by humans
function sumOfSquares (a, b) {
var x = add(a*a, b*b);
return x;
function add(c, d) {
var a = c + d;
return a;
}
}
// How javascript loads it
function sumOfSquares (a, b) {
// declared stuff is hoisted to the top of scope
// before operational code is run
var x = undefined;
function add(c, d) {
var a = c + d;
return a;
}
var x = add(a*a, b*b);
return x;
}
Function expressions are never hoisted. They are treated as assignments.
If using function expressions, place variable declarations and assignments at the top and put conditional code at the bottom. That way, variables are assigned immediately after being hoisted.
Or
Use declared functions as those will be hoisted and execution will occur later as conditionals fall to the bottom.