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.
π 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
π 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.