Skip to content

How to call a nested function in JavaScript | Example code

  • by

Generally defining a function inside another function is to scope it to that function and you can’t call a nested function in JavaScript.

function a() {
  function b() {
    alert('reached');
  }
}

You have to do something inside function to make the inner function available outside it. You will need to return the inner function call.

function a() {
  function b() {
    alert('reached');
  }
  return b();
}

Then you can call this function simply by calling the function a like this:

a();

Call a nested function in JavaScript

A simple example code calls function b() from outside of function a().

<!DOCTYPE html>
<html>
<body>
  <script>
    function f1() {
      var c = 0;
      function f2() {
        console.log(c++);
      }
      return f2;
    }
    var d = f1();
    d();
    d();
    d();
    var e = f1();
    e();
    e();
  
  </script>
</body>
</html>

Output:

How to call a nested function in JavaScript

Call nested function from outside function

You can’t call it from anywhere else unless you make it available somehow, for instance by assigning it to a property on the object you’re creating by calling batman via new:

function batman(){
    this.hello = function() {
        console.log("hello world!");
    };
}

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

Leave a Reply

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