JavaScript Nested Function

A nested function is a function that is completely contained within a parent function. In nested function the child function can access parents function scope. For example :
function ParentFunction() {
  function ChildFunction() {
    code to be executed
  }
}
To call child function from outside of the parent function, we need to use below code :
  ParentFunction.ChildFunction();
But before direct calling child function from outside of the parent function, first we need to call parent function and also add a single line code at end of parent function, which look like this :
  ParentFunction.ChildFunction = ChildFunction;
And the function structure would be :
function ParentFunction() {
  function ChildFunction() {
    code to be executed
  }
  ParentFunction.ChildFunction = ChildFunction;
}
Now Lets see an example of it.
<!DOCTYPE html>
<html>
<head>
  <title>Nested Function</title>
</head>
<body>
  <script>
    function message() {
      var text = prompt("Enter A Message : ");
      printmsg(text);
      function printmsg(msg) {
        document.getElementById('demo').innerText = msg;
      }
      message.printmsg = printmsg;   
    }
  </script>
  <input type="button" onclick="message()" value="Run Parent Function" />
  <input type="button" onclick='message.printmsg("Hello world From Child Function.")' value="Run Child Function" />
  <p id="demo"></p>
</body>
</html>
Output :



Note first click on the "Run Parent Function" button, then click on the "Run Child button".

Next Topic :