Search⌘ K

Nested Functions in JavaScript

Explore how nested functions work in JavaScript by declaring a function inside another. Understand how this structure improves variable accessibility within scopes and simplifies code through inner functions accessing outer variables without passing arguments.

In this lesson, we explore ways of writing nested functions.

Introduction to nested functions

We call functions nested when some function is declared inside another function.

Writing nested functions

The process to write nested functions is straightforward. We declare a function inside another function. Take a look at the following example.

Node.js
function outer (a){ // This is the outer function
console.log("Outer function executed with arg",a);
function inner(b){ // This is the inner function
console.log("Inner function executed with arg:",b);
return; // Exit inner function
}
inner(a); // Call inner function declared above
return; // Exit outer function
}
outer(1); // Call outer function declared above

In the code above, we declare two functions – outer and inner. We declared ...