Anonymous function assigned to variable vs a named function.

Let me explain today about the difference between anonymous function assigned to variable vs a named function. One important difference is how the function is hoisted.

With function foo(), the entire function is hoisted to the top of the surrounding scope. This means that you can call and reference a function before it's declared.

With var foo = function(), only the variable declaration is hoisted. This means that before the specific line, the function doesn't actually exist. Instead, var is "undefined" until that point. With let, however, your code throws an error. It will happen due to temporal dead zone. Code examples are here
console.log(foo);
let foo=function(){
};
//"ReferenceError: foo is not defined
console.log(foo);
var foo=function(){
};
//undefined
The temporal dead zone applies to const variable declarations as well. Another key difference in ES5 and lower is that you shouldn't ever create a named function within a block, because that function is hoisted. Assigning an anonymous function within a block works fine.
It is different in ES6. ES6 standardised function declarations in blocks. They use let bindings, and work mostly as you'd expect, but can't be referenced outside the block!
(function() {
  "use strict";

  { // Block
      console.log(typeof fn); // It's hoisted (function)
      function fn() {}
      console.log(typeof fn); //function (function)
  }
  console.log(typeof fn); // But not outside the block (undefined) 
})();

Share this post