DEV Community

Jarvis-3000
Jarvis-3000

Posted on

Difference between function declaration and function expression

A very important and confusing thing

//Function declarations load before any code execution
function foo() { return 5; }

//Anonymous function expression
//Load only when the interpreter reaches that line
var foo = function() { return 5; }

//Named function expression
var foo = function foo() { return 5; }

//Example: Function Expression

      alert(foo());    // ERROR! foo wasn't loaded yet
      var foo = function() { return 5; } 

//Example: Function Declaration

      alert(foo());    // Alerts 5. loaded before any code can run.
      function foo() { return 5; }

Top comments (0)