What is a Function Expression?
In JavaScript, a function expression is when a function is assigned to a variable. Unlike function declarations, function expressions are not hoisted, which means they are not available before the line they are defined.
Let’s look at a basic example:
const greet = function() {
console.log("Hello, world!");
};
greet(); // calling the function
Output:
Hello, world!
Here, we assigned an anonymous function (a function without a name) to the variable greet
. We can now use greet()
to execute that function.
Why Use Function Expressions?
- To store functions in variables.
- To pass them as arguments to other functions.
- To return them from other functions (used in closures).
Named Function Expressions
You can also name your function inside the expression. This can be useful for debugging purposes.
const sayHello = function greetUser() {
console.log("Hello from greetUser!");
};
sayHello();
Output:
Hello from greetUser!
Even though the function is named greetUser
, you still call it using sayHello()
because greetUser
is only available inside the function body.
Can I call a function expression before it's defined?
No. Function expressions are not hoisted like function declarations.
greet(); // Error: Cannot access 'greet' before initialization
const greet = function() {
console.log("Hi!");
};
This results in a ReferenceError because JavaScript doesn’t hoist function expressions. So you must define them before calling.
Function Expressions vs Function Declarations
// Function Declaration
function sayHi() {
console.log("Hi from declaration");
}
// Function Expression
const sayHiAgain = function() {
console.log("Hi from expression");
};
sayHi();
sayHiAgain();
Output:
Hi from declaration Hi from expression
Key Difference: Function declarations are hoisted to the top of their scope, meaning you can call them before their definition. Function expressions are not.
Example: Passing Function Expression as Argument
function execute(fn) {
fn(); // call the passed function
}
const printMessage = function() {
console.log("This is a function expression passed as an argument.");
};
execute(printMessage);
Output:
This is a function expression passed as an argument.
Example: Returning a Function Expression
function outer() {
return function() {
console.log("Returned from outer!");
};
}
const returnedFunction = outer();
returnedFunction();
Output:
Returned from outer!
Quick Question:
Q: Can you store a function expression inside an array or object?
A: Yes! Functions in JavaScript are first-class citizens.
const arr = [
function() { console.log("First function in array"); },
function() { console.log("Second function in array"); }
];
arr[0](); // calls the first function
Output:
First function in array
Points to Remember
- Function expressions are not hoisted.
- You can create anonymous or named function expressions.
- Function expressions can be used in variables, arrays, objects, and as return values.