A function expression is a function that is stored inside a variable.
Instead of giving the function a name directly, you assign it to a variable.
Example:
Here:
-
function()creates the function -
The function is assigned to the variable
greet -
You call it using
greet()
Simple Example of Function Expression
Explanation:
-
The function is stored in
sayHello -
Calling
sayHello()runs the function -
Output:
Function Expression with Parameters
Explanation:
-
aandbare parameters -
The function returns the sum
-
Output:
Function Expression with Return Value
Output:
25
Anonymous Function Expression
Most function expressions are anonymous, meaning they have no name.
This is common in:
-
Callbacks
-
Event handlers
-
Array methods (
map,filter, etc.)
| Function Declaration | Function Expression |
|---|---|
function greet() {} | const greet = function() {} |
| Can be used before definition (hoisted) | Cannot be used before definition |
| Common in basic programs | Common in modern JavaScript |
| Less flexible | More flexible |
Learning function expressions in JavaScript helps you:
-
Understand callbacks
-
Work with async code
-
Use array methods (
map,filter,reduce) -
Write modern JavaScript
-
Perform better in interviews
They are used everywhere in frameworks like React, Node.js, and Next.js.
Common Mistakes Beginners Make
Calling before defining
Correct usage
Function expressions in JavaScript are a powerful and flexible way to define functions. They allow you to store functions in variables, pass them as arguments, and use them in callbacks — which is essential in modern JavaScript development.