Skip to content

Function inside function JavaScript | Example code

  • by

Writing Function inside a function is called Nested function in JavaScript. A function can have one or more inner functions.

function a(x) {    // <-- function
  function b(y) { // <-- inner function
    return x + y; // <-- use variables from outer scope
  }
  return b;       // <-- you can even return a function.
}

These inner functions are under the scope of outer functions. The outer function can be called as Parent function and the inner function can be called as Child function. The child function can access variables and parameters of the Parent function.

However, the Parent function cannot access variables inside child functions.

Function inside function JavaScript

Simple example code one function inside another function.

<!DOCTYPE html>
<html>
<body>
  <script>
   function f1(x) {    
    console.log("Outer function ")

    function f2(y) { 
      console.log("Inner function")
      return x + y; 
    }

    return f2;       
  }

  console.log(f1(200)(100))
</script>

</body>
</html> 

Output:

Function inside function JavaScript

Do 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 *