Function expressions are a powerful feature in JavaScript that allow you to create and assign functions to variables. They provide flexibility and enable you to write more concise and expressive code.
A function expression is a way to define a function as part of an expression. Unlike function declarations, function expressions are not hoisted and can be anonymous (without a name).
The basic syntax of a function expression is as follows:
const functionName = function(parameters) {
// function body
return result;
};
Function expressions often create anonymous functions, which are functions without a name:
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet('Alice')); // Output: Hello, Alice!
You can also give a name to function expressions, which can be useful for debugging:
const factorial = function fact(n) {
if (n <= 1) return 1;
return n * fact(n - 1);
};
console.log(factorial(5)); // Output: 120
While function expressions and function declarations are similar, they have some key differences:
Function Expressions | Function Declarations |
---|---|
Not hoisted | Hoisted to the top of their scope |
Can be anonymous | Must have a name |
Can be assigned to variables | Cannot be directly assigned to variables |
Function expressions are often used in the following scenarios:
map()
or filter()
By mastering function expressions, you'll gain a powerful tool for writing flexible and efficient JavaScript code. They are essential for advanced programming techniques and are widely used in modern JavaScript development.