JavaScript function inside function |nested/inner example code

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:

JavaScript function inside function

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.