In recent versons of JavaScript, nested function definitions within other functions ar supported. Still there is a restriction that function definitions may not appear within loops or conditionals. These restrictions on function definitions apply only to function declarations with the function statement.
Let us see some examples to understand it’s implementation:
function hypotenuse(a, b) {
function square(x) { return x*x; }
return Math.sqrt(square(a) + square(b));
}
var result = hypotenuse(1,2);
Here inside the function hypotenuse we have another nested function square which returns the square of a number. So in this way we may use the nested functions and sometimes it is very useful to use them.
Let us see another example where we will pass the argument for nested function:
function fun1(a) {
function fun2(b) {
return a + b;
}
return fun2;
}
var x = fun1("Adarsh") (" Chaudhary");
Here while calling function fun1, we are passing two arguments one for the fun1 and other for the nested function fun2. As a result of which finally it will store Adarsh Chaudhary in the variable x.
Now cosider the following code snippet and write it’s output:
function fun1(a) {
a *= 2;
function fun2(b) {
return a + b;
}
a += 2;
return fun2;
}
function fun3(){
return fun1(2) (2);
}
console.log(fun3());