Can you write nested functions in JavaScript?
Yes, You can write a function inside the function in JavaScript. JavaScript supports writing a function within another function, or nested functions.
Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable. This is especially important for use with closures to reduce total global namespace pollution.
Simple code snip (code structure)
function math(x) { // <-- function
function sum(y) { // <-- inner function
return x + y; // <-- use variables from outer scope
}
return b; // <-- you can even return a function.
}
console.log(a(3)(4));
JavaScript function inside function Example code
HMTL example code of nested/inner function:-
<!DOCTYPE html>
<html>
<head>
<script>
function outer() {
console.log("Outer function");
function inner() {
console.log("Inner function")
}
inner(); // call it
}
// call functions
outer();
</script>
</head>
<body>
</body>
</html>
Output:
Note: Nested function and inner function both are the same terms used for function inside function in programming.
Do comment if you have any doubts and suggestions on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version
This is one complex example I’ve got here…
You have 2 functions: “math” and “sum”, so far so good, then you return “b”…wtf, where did that come from? is “b” a built-in javascript function, that just magically exists?
And then you execute function “a”…huh?
I don’t know what audience this is targeted for, but it’s definitely not for beginners.
You can do it, just pay little attention.