Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER

# Nested Functions

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());
Hints
• Hints are not available for this problem

## Discussion

Free Mock Assessment
Fill up the details for personalised experience.
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
*Enter the expected year of graduation if you're student
Current Employer
Company Name
College/University Name
Job Title
Job Title
Software Development Engineer (Backend)
Software Development Engineer (Frontend)
Software Development Engineer (Full Stack)
Data Scientist
Android Engineer
iOS Engineer
Devops Engineer
Support Engineer
Research Engineer
Engineering Intern
QA Engineer
Co-founder
SDET
Product Manager
Product Designer
Backend Architect
Program Manager
Release Engineer