42. Function Expressions
A function expression is created when a function is defined as part of an expression, usually by assigning an anonymous function (a function without a name) to a variable.
Syntax
javascript const functionName = function(parameter1) { // code block };
Example: Calculation Expression
javascript const calculateArea = function(width, height) { return width * height; };
let area = calculateArea(5, 4); console.log(area); // Output: 20
Function Expressions vs. Declarations
| Feature | Declaration | Expression |
|---|---|---|
| Syntax | function name() {} | const name = function() {} |
| Hoisting | Function is fully hoisted. | Only the variable name is hoisted, not the definition. |
| Usage | Preferred for standalone functions. | Preferred for callbacks, passing functions as arguments, or when definition order matters. |
Note: Function expressions do not allow you to call the function before it is defined in the script.