What is the difference between a function declaration and a function expression?
A declaration is hoisted with its body, so you can call it before the line it appears on. An expression assigns a function to a variable, and the variable follows var, let or const rules, so calling it early fails.
Explain it simply
A declaration is like a printed entry in a college directory: it exists from the start, so anyone can look it up even before the page where it is written. An expression is like a name added to a list on the day you actually reach that line.
function greet() {} // declaration
const greet2 = function () {}; // expressionWith a declaration, the whole function is hoisted to the top of its scope. With an expression, only the variable is hoisted: var gives undefined until assignment, and let or const throw a ReferenceError in the temporal dead zone.
Example
console.log(add(2, 3)); // Output: 5
function add(a, b) {
return a + b;
}
try {
console.log(mul(2, 3));
} catch (e) {
console.log(e.name); // Output: ReferenceError
}
const mul = function (a, b) {
return a * b;
};With var mul = function... the error would be a TypeError ("mul is not a function"), because mul would be undefined at that point.
What to say in the interview
"Declarations are fully hoisted, so they can be called before they appear. Expressions are values assigned to a variable, so only the variable is hoisted and the function is unavailable until that line runs. Arrow functions are always expressions."
Common mistakes
- Saying that function expressions are not hoisted at all. The variable is hoisted, the function value is not.