Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Function declaration “function foo()” vs function expression “const foo = function()” ?

At a first glace writing the below two lines of Javascript seem to have the same effect.

function foo() { return 1; }
const foo = function() { return 1; }

The first one is a function declaration meanwhile the second is a function expression.

// a function declaration
function foo() { return 1; }

// a function expression
const foo = function() { return 1; }

In order to make it easier to remember we can consider the following rule, taken from this excellent article of Dmitri Pavlutin:

"If the statement starts with the function keyword, then it’s a function declaration, otherwise it’s a function expression."

Now, if we put the two lines in a context we will see there is a subtle difference between them:

// this will print 1
console.log(foo());
function foo() { return 1; }

// this will result in an Uncaught ReferenceError
console.log(foo());
const foo = function() { return 1; }

And this is because function declarations load before any code is executed while function expressions load only when the interpreter reaches that line of code. Or in other words, function declarations are hoisted to the top of other code.