Skip to content

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.

JavaScript function inside function Example code

HMTL example code of nested/inner function:-

<!DOCTYPE html>

        function outer() { 

            console.log("Outer function");

            function inner() {
                console.log("Inner function")

            inner(); // call it

        // call functions




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

2 thoughts on “JavaScript function inside function |nested/inner example code”

  1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *