Writing a Function inside a function is called a Nested function in JavaScript. A function can have one or more inner functions. This concept is known as closures.
function a(x) { // <-- function
function b(y) { // <-- inner function
return x + y; // <-- use variables from outer scope
}
return b; // <-- you can even return a function.
}
These inner functions are under the scope of outer functions. The outer function can be called a Parent function and the inner function can be called the Child function. The child function can access the variables and parameters of the Parent function.
However, the Parent function cannot access variables inside child functions.
Function inside function JavaScript
Simple example code one function inside another function.
<!DOCTYPE html>
<html>
<body>
<script>
function f1(x) {
console.log("Outer function ")
function f2(y) {
console.log("Inner function")
return x + y;
}
return f2;
}
console.log(f1(200)(100))
</script>
</body>
</html>
Output:
Closures are powerful because they allow inner functions to “remember” the environment in which they were created, even if they are called outside that environment. This can be useful for creating private variables and functions.
Note: The inner function can access variables from the outer function, but the reverse is not true. The outer function cannot directly access variables from the inner function.
Comment if you have any doubts or suggestions on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version