You can create JavaScript nested functions by writing one function inside another function. Make a call to the inner function in the return statement of the outer function.
function A(){
B(); //call should be B();
function B(){
//code
}
}
Here’s an example of how to create and use nested functions:
function outerFunction() {
const outerVariable = "I'm from the outer function";
function innerFunction() {
const innerVariable = "I'm from the inner function";
console.log(outerVariable); // Accessing the outer variable
console.log(innerVariable); // Accessing the inner variable
}
innerFunction(); // Call the inner function
}
outerFunction(); // Call the outer function
In this example, we have an outerFunction
containing an innerFunction
. The innerFunction
can access variables from the outerFunction
, such as outerVariable
, because it’s nested inside the outerFunction
. When you call outerFunction
, it also calls innerFunction
from within it.
JavaScript nested function
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
function fun1(a) {
function fun2(b) {
return a + b;
}
return fun2;
}
function final() {
console.log(fun1('Outer')(' + Nested Function'))
}
final();
</script>
</body>
</html>
Output:
Different ways to create and use nested function
<script>
function fun1(a) {
fun = function fun2(b) {
return a + b;
}
return fun;
}
function final() {
console.log(fun1('Hello')(' Function'))
}
final();
</script>
Output: Hello Function
Write output on the HMTL page
<script>
function hypotenuse(a, b) {
function square(x) { return x*x; }
return Math.sqrt(square(a) + square(b));
}
function secondFunction() {
var result;
result = hypotenuse(1,2);
document.write (result);
}
secondFunction();
</script>
Output: 2.23606797749979
Can you write nested functions in JavaScript?
Answer: Yes, it is possible to write and call a function nested in another function. You can also use it for calculation inside but define it outside.
There is a restriction that function definitions may not appear within loops or conditionals.
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.
}
console.log(a(3)(4));
What’s the need and use of nested functions in JavaScript?
Answer: The core importance of nested functions is scope generation and achieving the following.
- Non-Polluted Global Namespace
- Modularization of functionality
- Encapsulate private internal workings of modules
- Prevent collision of identifiers across different scripts
- Smaller script sizes because variables inside nested scopes qualify for minification.
- It speeds up the Identifier Resolution Process
Source: stackoverflow.com
Do 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