JavaScript

JavaScript Nested Functions

JavaScript nested functions are the types of functions defined within another function. One or more functions can be added inside a function, and the scope of the outer functions includes these nested or inner functions. The outer functions are also referred to as the Parent functions, and the inner functions can be named as Child functions in JavaScript nested functions. The variables and parameters of the parent function are accessible to the child function, whereas the parent function cannot access the variables declared inside the child functions.

This write-up discussed JavaScript Nested Functions. Moreover, we have also explained the variable scope, Parameters, and return statements of the nested functions with the help of the examples.

JavaScript Nested Functions

In JavaScript, a nested function is a function that is defined inside or within another function. The procedure for creating a nested function is the same as we follow for the normal function, but to create a nested function, we have to define the new or the child function inside the parent function.

Here is the syntax of JavaScript Nested functions:

Function parentFunction()//function definition
{
Function childFunction()//function definition
{
//body of the child function
}
childFunction();// child function calling
}
parentFunction();//parent function calling

As you can see from the syntax, we have to define the childFunction() within the parentFunction(). Also, when we want to invoke the childFunction(), we have to call it within the body of the parentFunction().

Example: Using JavaScript Nested Functions

This example will show you how to create JavaScript nested functions. For this purpose, we will define a parent function named “addNum()”, which has two parameters, “x” and “y”. After doing so, we will create a child function “showMessage()” which prints out a text message to the console window:

function addNum(x,y)
{
  //nested function
  function showMessage(text)
  {
  console.log(text);
  }
  let sum=x+y;
  //invoking the nested function
  showMessage("sum is "+ sum)
}

Note that we have called the “showMessage()” function inside the function definition of the “addNum()” function. In the next step, we will call the parent function addNum() while passing “5” and “6” as arguments:

addNum(5,6)

As you can see from the output, we have successfully executed the nested functions of our example:

Variable scope of JavaScript Nested Functions

Now, let’s talk about the scope of the nested functions in JavaScript. The nested functions have their own scope; however, they can also access the scope of the parent or outer function. You should keep in mind two points about the variable scope of JavaScript nested functions: A nested function is private for its parent function, and a nested function has access to the parent function’s scope.

We will explain each of the given statements with the help of examples.

As we have stated, the nested function is considered “private” for the function that contains its definition. It means only the parent or the containing function can access the nested function, and you will not be permitted to access it outside of the specified function. This happens because we have defined the inner function inside of the outer function scope.

For instance, we have defined an outer function “AddNumber()” in the below-given code and then added the inner function “showMessage()” within the definition of the outer function:

function addNumber(x,y)
{

  function showMessage(text)
  {
    console.log(text);
  }

  let sum=x+y;
showMessage("sum is " + sum)
}

Now, when we try to access the inner function “showMessage()” outside of its scope, it will throw the “Uncaught ReferenceError” error:

showMessage('20');

All of the functions, variables, and arguments defined in the outer function are accessible to the created nested function. This ability is known as “Lexical scope”, where the inner function can access the scope of the parent or outer function.

We will not pass any arguments to our showMessage() inner function in the below-given example. What we will do is to utilize the arguments “x” and “y” of our “addNumber()” outer function and the “sum” variable:

function addNumber(x,y)
{

  function showMessage()
  {
    console.log(`sum of %d + %d is %d`,x ,y,sum);
  }

  let sum=x+y;
  showMessage()
}

Now, we will invoke the outer function “AddNumber()” and pass the “4” and “6” as arguments:

addNumber(4,6)

Have a look at the below-given output, which signifies that we have successfully accessed the “sum” variable, “x”, and “y” argument of the addNumber outer function in the showMessage() function:

Returning a JavaScript Nested Function

The outer function has the capability to return the nested function. For instance, in the below-given example, the displayCounter() function have a “count” variable and returns the increment() inner function:

function displayCounter() {
  let count = 0;

  increment = function () {
    return ++count;
  };

  return increment;
}

We will store the displayCounter() function in the “counter” in the next step. Now the concept we need to discuss here is that the “increment()” function will still have access to the “count” property of the “displayCounter()” function when the displayCounter() finished the execution. “Closure”, a JavaScript feature, makes this possible.

Here the “count” property is local to the “displayCounter()” function, however, the defined “increment” function can also access it because it is nested inside the “displayCounter()” function:

counter = displayCounter()

The above-given code will call out the “displayCounter()” function. Then, the displayCounter() function will first initialize the “count” variable to the “0” value and then returns the “increment()” function. Because the “count” property is not destroyed, when we will call the increment function through the “counter()”, each time the “count” property will be incremented according to the added code:

console.log(counter());
console.log(counter());
console.log(counter());

Check out the below-given output of the provided example:

Parameters of JavaScript nested functions

The inner function can also take arguments. For instance, in the following example, the “innerFunction()” is returned by the “outerFunction()” and each of them accepts an argument set:

function outerfunction(x) {

  innerFunction = function (y) {
    console.log("x %d  y %d",x,y)
  };

  return innerFunction;
}

To get the innerFunction(), we will add the following code in our JavaScript program while passing “3” as an argument for the outerFunction():

InnerFunction=outerfunction(3);

Then, we will invoke the innerFunction() with value “7” as an argument:

InnerFunction(7);

You can also pass the arguments for both outer and inner functions at once:

outerfunction(2)(3);

Both of the specified lines of the code invoked the innerFunction() and output the passed arguments:

Conclusion

JavaScript permits you to use nested functions in the program without encountering errors. A child or inner function can be added inside an outer function in JavaScript. All of the local, global variables of the outer function are accessible to the inner function. In the case of the outer function, only global properties values and the methods and variables defined in the parent functions are accessible. This write-up discussed JavaScript Nested Functions. Moreover, we have also explained the variable scope, Closure property, Lexical scope, Parameters, and return statements of the JavaScript nested functions, with the help of the examples.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.