JavaScript nested functions are functions declared inside other functions. They help organize code, reuse functionality, and access variables from outer functions. Nested functions are commonly used in callbacks, closures, and other advanced JavaScript concepts.
In this tutorial, you will learn what nested functions are, how they work, and how to use them with simple examples.
What Are Nested Functions in JavaScript?
A nested function is a function defined inside another function. The outer function contains the inner function, which can be called from within the outer function.
Example of a Nested Function
function outerFunction() {
function innerFunction() {
console.log("Hello from the inner function!");
}
innerFunction();
}
outerFunction();
Output:
Hello from the inner function!
In this example, innerFunction() is declared inside outerFunction(). Calling outerFunction() executes the inner function.
Accessing Outer Function Variables
An inner function can access variables declared in its outer function because JavaScript uses lexical scoping.
function outerFunction() {
let message = "Welcome to Web4Learners!";
function innerFunction() {
console.log(message);
}
innerFunction();
}
outerFunction();
Output:
Welcome to Web4Learners!
Here, innerFunction() accesses the message variable declared in outerFunction().
Learn more about JavaScript Function Scope to understand how variables are accessed within functions.
Nested Functions with Parameters
Nested functions can accept parameters and perform calculations like regular functions.
function calculateTotal(price) {
function addTax() {
return price + price * 0.10;
}
return addTax();
}
console.log(calculateTotal(100));
Output:
110
The inner function adds 10% tax to the price and returns the result to the outer function.
Benefits of Nested Functions
- Code organization: Keep helper functions close to where they are needed.
- Variable access: Inner functions can use variables from their outer functions.
- Encapsulation: Inner functions can remain private to the outer function.
- Reusability: Inner functions can perform specific tasks within the outer function.
Frequently Asked Questions
Can a nested function access outer variables?
Yes. An inner function can access variables from its enclosing function through lexical scoping.
Can we call an inner function outside its outer function?
Generally, no. An inner function declared locally is accessible only within its enclosing scope unless it is returned or otherwise exposed.
Are nested functions useful in JavaScript?
Yes. They help organize code, create private helper functions, and support concepts such as closures and callbacks.