JavaScript Function Expression
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.
- 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("Ananya"));
Output
Hello, Ananya!
In this code
- 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.
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));
Output
8
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));
Output
120
Use Cases of Function Expressions
1. Storing in Variables
Function expressions are often assigned to variables for easy reuse.
const add = function(x, y) {
return x + y;
};
console.log(add(3, 5));
Output
8
2. Callback Functions
They are commonly used as arguments in higher-order functions.
setTimeout(function() {
console.log("This message appears after 3 seconds!");
}, 3000);
Output
This message appears after 3 seconds!
3. Event Handlers
Function expressions are ideal for event listeners.
document.querySelector("button").addEventListener("click", function() {
console.log("Button clicked!");
});
Output
[ 1, 4, 9, 16 ]
4. Self-Invoking Functions
Function expressions can be immediately executed.
(function() {
console.log("This is a self-invoking function!");
})();
Output
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));
Output
12
Key Features:
- Implicit return for single-line functions.
- No binding of this, making them unsuitable for methods requiring a this context.
Function Expression vs Declaration
Feature | Function Expression | Function Declaration |
---|---|---|
Hoisting | Not hoisted; defined at runtime. | Hoisted; can be called before definition. |
Syntax | Defined within an expression. | Uses function keyword with a name. |
Usage | Useful for callbacks and dynamic functions. | Best for defining reusable functions. |