What is a Function Declaration?
According to the MDN docs, "the function declaration (function statement) defines a function with the specified parameters".
function addNums(a, b) {
return a + b;
}
console.log(addNums(5, 6)); //11
What is a Function Expression?
According to the MDN docs, "the function keyword can be used to define a function inside an expression".
const addNums = function (a, b) {
return a + b;
};
console.log(addNums(5, 6)); //11
Difference - Hoisting
The biggest difference between function declaration and function expression is hoisting.
- Function Declaration - Hoisted (Hoisted to the top of the enclosing function or global scope)
- Function Expression - Not hoisted
//Function Declaration
hoisted(); //"foo"
function hoisted() {
console.log('foo');
}
//Function Expression
notHoisted(); // TypeError: notHoisted is not a function
const notHoisted = function () {
console.log('bar');
};
Reference
When to use a function declaration vs. a function expression