Your code is equivalent to this:
// function declarations are hoisted
function fn1(message) {
console.log('mgs1:', message);
}
// variable declarations are hoisted
var fn2;
fn1('hello');
fn2('world');
// assignments to a variable are not hoisted
fn2 = function(message) {
console.log('msg2:', message);
}
The declaration of the fn1
function is hoisted.
The declaration of the fn2
variable is hoisted.
The assignment to the fn2
variable is not hoisted.
Declarations are hoisted, assignments or initializations are not.
Function assignments like you are doing with fn2
are different than function declarations such as fn1
. Assignments to variables with var
are not hoisted, only the definition of the variable itself is hoisted. So, at the point you try to call fn2('world')
, fn2
is still undefined
.