Functions as Values
Function expressions assign a function to a variable.
They are not hoisted like declarations, so you must define them before use.
JavaScript Tutorial
A function expression assigns a function to a variable.
Unlike declarations, expressions are not hoisted with their bodies.
Function expressions give you flexibility to pass functions around and assign them conditionally.
They are especially common in callbacks and higher-order patterns.
const name = function(params) { ... };const greet = function(name) {
return "Hello " + name;
};
console.log(greet("Sam"));Assign a function to a variable.
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
console.log(factorial(4));Named expressions help recursion and debugging.
Function expressions assign a function to a variable.
They are not hoisted like declarations, so you must define them before use.
Expressions can be anonymous or named for better stack traces.
Named expressions help debugging without adding a new variable.
Use function expressions for callbacks, configuration, and conditional assignments.
They are common in event handlers and functional patterns.
const mode = "compact";
const formatter = mode === "compact"
? function(value) { return value.toFixed(0); }
: function(value) { return value.toFixed(2); };
console.log(formatter(12.345));Assign different functions based on conditions.
const nums = [1, 2, 3];
const doubled = nums.map(function(n) {
return n * 2;
});
console.log(doubled);Function expressions are common in callbacks.
Without
function add(a, b) {
return a + b;
}With
const add = function(a, b) {
return a + b;
};Function expressions are not hoisted like declarations.
Name functions for better debugging when appropriate.
Pick a consistent style for readability.
Function expressions are not hoisted with their bodies.
They improve stack traces and allow recursion.
For callbacks, event handlers, and conditional assignments.
Practice: Create a function expression that returns the square of a number.
// TODO: const square = function(n) { ... }
One Possible Solution
const square = function(n) {
return n * n;
};
console.log(square(6));The variable is hoisted, but the function value is not.
They are flexible and work well for callbacks and conditional assignments.
Yes, named expressions help debugging and recursion.
Try calling the function after definition with different inputs.