Today, I learned about the difference between a function declaration and function expression (link). A function declaration is a function that is declared with the function keyword.
I also learned about a concept called hoisting. Hoisting is a concept in which the JavaScript interpreter moves variable and function declarations to the top of their containing scope during the compilation phase. This means that a variable can be used before it is declared. A function declaration is hoisted to the top of the scope in which it is declared, so it can be called before it is defined. A function expression on the other hand is a function that is assigned to a variable. It is not hoisted, so it must be defined before it is called. If you try to call a function expression before it is defined, you will get an error.
Here are some examples of function declaration vs function expression
// Function Declaration
function addDollarSign(value) {
return '$' + value;
}
console.log(addDollarSign(100)); // $100
// Function Expression
const add = function addPlusSign(value) {
return '+' + value;
}
console.log(addPlusSign(100)); // +100
//Hoisting
console.log(square(5)); // 25 //Function is called before it is declared
function square(n){
return n * n;
}
console.log(square(5)); // Error //Function is called before it is declared
const square = function(n){
return n * n;
}