A function expression is a way to define a function by assigning it to a variable or using it within an expression, allowing the function to be stored, passed as an argument, or executed immediately.
- Function expressions can be named or anonymous.
- They are not hoisted, meaning they are accessible only after their definition.
- Frequently used in callbacks, closures, and dynamic function creation.
- Enable encapsulation of functionality within a limited scope.
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet("Steven"));
- The function(name) creates an anonymous function assigned to the greet variable.
- The function takes name as a parameter and returns a greeting string.
- Calling greet("Ananya") invokes the function and outputs the greeting.
Syntax
const fName = function(params) {
// function body
};
- fName: Variable storing the function.
- function(params): Defines the function. Parameters are optional.
- { // function body }: Contains the logic to execute when the function is called.
A function expression is a way to define a function as part of an expression making it versatile for assigning to variables, passing as arguments, or invoking immediately.
Named vs Anonymous Function Expressions
Anonymous Function Expression: The function has no name and is typically assigned to a variable.
const sum = function(a, b) {
return a + b;
};
console.log(sum(5, 3));
Named Function Expression: The function is given a name, which is useful for recursion or debugging.
const factorial = function fact(n) {
if (n === 0) return 1;
return n * fact(n - 1);
};
console.log(factorial(5));
Use Cases of Function Expressions
1. Storing in Variables
Function expressions can be stored in variables so they can be reused easily whenever needed.
const add = function(x, y) {
return x + y;
};
console.log(add(3, 5));
2. Callback Functions
Callback functions are functions passed as arguments to other functions and are executed later when needed.
setTimeout(function() {
console.log("This message appears after 3 seconds!");
}, 3000);
3. Event Handlers
Function expressions are useful for event listeners because they allow you to define a function directly where it is needed.
document.querySelector("button").addEventListener("click", function() {
console.log("Button clicked!");
});
4. Self-Invoking Functions
Function expressions can be immediately executed.
(function() {
console.log("This is a self-invoking function!");
})();
Advantages of Function Expressions
- Flexibility: Can be used as callbacks, event handlers, or part of expressions.
- Encapsulation: Keeps the scope limited and avoids polluting the global namespace.
- Control Over Execution: Executes only when explicitly invoked.
Arrow Functions: A Variant of Function Expressions
Arrow functions are a concise and modern way to define function expressions. They are particularly useful for short, single-purpose functions.
const arrowFunc = (param1, param2) => param1 + param2;
console.log(arrowFunc(5, 7));
Features:
- Implicit return for single-line functions.
- No binding of this, making them unsuitable for methods requiring a this context.
Difference Between Function Expression and Function Declaration
Here are some difference between Function expression and Function Declaration:
| Function Expression | Function Declaration |
|---|---|
| Function Expression cannot be hoisted, so they can be called before their definition. | Function Declaration are Hoisted so that can be called before their definition. |
Can be passed as arguments or stored in variables | Typically used as standalone functions |
| Defined within an expression. | Uses function keyword with a name. |
| Useful for callbacks and dynamic functions. | Best for defining reusable functions. |
Can be assigned to variables or passed as arguments | Typically used as standalone functions |