JavaScript: Nested Functions

Profile picture for user arilio666

In this article, we will see how we can nest a function. A nested function is nothing but using a function inside a function. When you put a nested function inside a function, the inner function/nested function is private to the containing outer function.

function addSq(x,y)
{
    function sq(z)
    {
        return z * z;
    }
    return sq(x) + sq(y);
}
console.log(addSq(2,4))

Output: 20

  • Here, in a nested function, sq() which is nested within addsq(), is only activated with the outer function rather than the inner one.
  • Also, we gave some parameters for addsq(x,y); the main goal is to square the number.
  • And, we create a nested function with that and give one parameter so that the primary function will return the nested function name, which is sq and within it the parameter of the primary function.
  • Which will be eventually passed inside the sq() function when returns add the nested square and give out the result.

It is a simple program and concept; practical work on it will definitely aid the confusion around the nested function. It is an excellent concept of using the main function parameter and utilizing it for the nested one.