Junior
What do you know about the differences between function expressions and function declarations?
sobes.tech AI
Answer from AI
A function expression can be either named or anonymous. A function declaration always has a name.
The main difference is the hoisting mechanism:
- Function declaration: Fully hoisted, including its body. The function is available for calling in the code before its actual declaration.
- Function expression: Only the variable it is assigned to is hoisted (if
varis used). The function itself is only available after the interpreter reaches its line. Withletandconst, there is no hoisting even for the variable.
// Function declaration
console.log(declarationFunc()); // Works, function is hoisted
function declarationFunc() {
return "I am a declaration";
}
// Function expression
// console.log(expressionFunc()); // Will throw TypeError or ReferenceError (depends on var/let/const)
const expressionFunc = function() {
return "I am an expression";
};
console.log(expressionFunc()); // Works after definition
Function declarations are preferable for regular use because their order in the code does not affect the ability to call them. Function expressions are often used for:
- Creating anonymous functions (for example, as arguments or immediately invoked function expressions - IIFE).
- Conditional function definitions.
- Creating closures.