Introduction
Function expressions are a way of defining functions in JavaScript by assigning them to variables. Unlike function declarations, function expressions are not hoisted, meaning they cannot be used before they are defined in the code.
They are widely used in modern JavaScript for callbacks, event handling, and creating flexible code structures.
What is a Function Expression
A function expression defines a function inside an expression and stores it in a variable. It can be anonymous or named.
Example
const greet = function() {
console.log("Hello, world");
};
greet();
Here the function is stored in a variable called greet and called using that variable.
Named Function Expression
A function expression can also have a name which is useful for debugging.
const greetUser = function welcome() {
console.log("Welcome user");
};
greetUser();
The function is still accessed through the variable even if it has an internal name.
Key Features of Function Expressions
Functions are stored in variables
They are not hoisted
They can be anonymous or named
They are commonly used in callbacks
They support flexible programming patterns
Difference Between Function Declaration and Function Expression
Function Declaration
function sayHello() {
console.log("Hello");
}
Function Expression
const sayHello = function() {
console.log("Hello");
};
Function declarations can be used before they are defined but function expressions cannot.
Use Cases of Function Expressions
Event handling in websites
Callback functions like map and filter
Storing functions in variables
Creating reusable code blocks
Asynchronous programming
Example with Callback
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled);
Advantages
Makes code flexible
Helps in writing clean structure
Important for modern frameworks
Useful in functional programming
Conclusion
Function expressions are an important part of JavaScript that help developers write flexible and reusable code. They are widely used in real-world web development.