What is Function Expression in JavaScript: Simple Explanation
function expression in JavaScript is when you create a function and assign it to a variable. Unlike function declarations, function expressions are not hoisted and can be anonymous, meaning they don't need a name.How It Works
Think of a function expression like writing a recipe and putting it inside a labeled jar (a variable). You can then use the jar's label to follow the recipe whenever you want. This means the function is stored as a value inside the variable.
Unlike a function declaration, which is like a recipe posted on the kitchen wall and ready to use anytime, a function expression only exists after the line where you assign it. So, you can't use it before that point.
This allows you to create functions dynamically and pass them around like any other value, making your code flexible and powerful.
Example
This example shows a function expression assigned to a variable and then called to print a greeting.
const greet = function(name) { return `Hello, ${name}!`; }; console.log(greet('Alice'));
When to Use
Use function expressions when you want to create functions dynamically or pass them as values to other functions. They are useful for callbacks, event handlers, or when you want to keep functions private inside another function.
For example, when you want to run some code after a button click, you can pass a function expression as the click handler. Also, function expressions help in writing cleaner and more modular code.
Key Points
- Function expressions are functions stored in variables.
- They can be anonymous (no name).
- They are not hoisted, so you must define them before use.
- Useful for callbacks and dynamic function creation.