0

I stumbled upon this jsfiddle code sample about hoisting https://jsfiddle.net/phusick/h4bh2m4y/

fn1('hello');
fn2('world');

function fn1(message) {
    console.log('mgs1:', message);
}

var fn2 = function(message) {
    console.log('msg2:', message);
}

Surprisingly it does not work :

Uncaught TypeError: fn2 is not a function

Is there any error in that program ?

user310291
  • 33,174
  • 71
  • 241
  • 439
  • var declared functions have to be declared before they are called, named functions can be found anywhere in your code – Icepickle Aug 08 '16 at 09:15
  • 2
    Possible duplicate of [JavaScript function declaration syntax: var fn = function() {} vs function fn() {}](http://stackoverflow.com/questions/336859/javascript-function-declaration-syntax-var-fn-function-vs-function-fn) – haim770 Aug 08 '16 at 09:15

2 Answers2

7

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.

jfriend00
  • 580,699
  • 78
  • 809
  • 825
5

Function declarations are hoisted. (function fn1(message) { })

Variable declarations are hoisted. (var fn2)

Assignments are not hoisted. (fn2 = function(message) { })

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205