JavaScript: What's the Difference Between Function Declaration and Function Expression

Want to master JavaScript in a week? Buy Xah JavaScript Tutorial.

What's the difference between function declaration and function expression?

function f () {};


var f = function () {};

Function Declaration → Hoisting Name & Value

Function declaration will hoist the function name and definition to the top, but function expression assigned to variable will only hoist the name, not the definition.


// works
console.log(f()); // 1
function f () {return 1;};
// TypeError: undefined is not a function
var f = function f () {return 1;};

this is important when you use recursion. Example:

console.log(m()); // [Function: m]

function m() { return m; }
console.log(m()); // TypeError: undefined is not a function

var m = function () { return m; }

You can also write:

var f = function g () {};


var f = function f () {};

The technical detail is fairly complicated. See: 〔Named function expressions demystified By Juriy “Kangax” Zaytsev. @

Thanks to ЮрийТарабанько and Paul Oldridge.

blog comments powered by Disqus