Function Declarations and Expressions
There are two classic ways to define a function: a declaration and an expression, and they behave differently when it comes to hoisting.
function greet(name) {
return `Hello, ${name}!`;
}
const greetExpr = function (name) {
return `Hi, ${name}!`;
};
greet("Rahim"); // works even if called before its definition — hoisted
greetExpr("Karim"); // must be defined before this line runs
Function declarations are fully hoisted — both the name and the body — so they can be called earlier in a file than where they're written. Function expressions are only hoisted as a variable declaration; the function itself is assigned at the line where the expression appears, so calling greetExpr before that line throws a TypeError.
In practice, many teams prefer function expressions (or arrow functions) assigned to const for consistency with how other values are declared, while still using declarations for top-level, broadly-used utility functions.