Javascript Nested Functions – Function In A Function!?

INTRODUCTION

MYSTERY NESTING

Welcome to a beginner’s tutorial on nested functions in Javascript. This is a rather interesting question that I found in Quora, and one that is pretty common – Can we define functions in a function? What are the uses and why would we want to do that? For a quick answer:

Yes, we can define functions inside a function – These are called nested functions. The idea of doing so is to contain the scope of the nested functions within the parent function; Nested functions will not exist outside of the parent function, they are only useful within the parent function itself.

But just what does that mean? What practical uses are there? Let us walk through all of that in this guide – Read on to find out!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

 

PREAMBLE

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

There is nothing to install, so just download and unzip into a folder. If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

SECTION A

FUNCTION BASICS

All right, let us now start with a quick recap and walkthrough – There are 4 ways we can define functions in Javascript. Feel free to skip this section if you already know.

 

FUNCTION DECLARATION

1-basic-functions.html
function myFunctionA (param) {
  console.log(param);
}
myFunctionA("Hello");

This is probably the most “traditional” way to create functions that we know of, the very first thing that we learn since day one of Javascript.

 

FUNCTION EXPRESSION

1-basic-functions.html
var myFunctionB = function (param) {
  console.log(param);
};
myFunctionB("World");

Next, we have a more “variable-like” way to create function.

 

 

FUNCTION CONSTRUCTOR

1-basic-functions.html
var myFunctionC = new Function (
  "param", "console.log(param)"
);
myFunctionC("Foo");

Huge fan of object-oriented programming? Here is how we create functions using the new Function() constructor.

 

ARROW FUNCTION

1-basic-functions.html
var myFunctionD = (param) => {
  console.log(param);
};
myFunctionD("Bar");

Finally starting from ECMAScript 2015 onwards, we have something called an “arrow function”, or a shorthand way to define functions.

 

SECTION B

FUNCTION NESTING

So far so good? Now that we have gone through a quick refresher for Javascript functions, let us walk through a few actual examples of nested functions.

 

BASIC NESTED FUNCTIONS

2-basic-nesting.html
function myFunction () {
  // (A) FUNCTION DECLARATION
  function insideA (param) {
    console.log(param);
  }
  insideA("Hello");

  // (B) FUNCTION EXPRESSION
  var insideB = function (param) {
    console.log(param);
  };
  insideB("World");

  // (C) FUNCTION CONSTRUCTOR
  var insideC = new Function (
    "param", "console.log(param)"
  );
  insideC("Foo");

  // (D) ARROW FUNCTION
  var insideD = (param) => {
    console.log(param);
  };
  insideD("Bar");
}
myFunction();

// (E) NESTED FUNCTIONS WILL NOT EXIST "OUTSIDE"
console.log(insideA); // Reference Error
console.log(insideB); // Reference Error
console.log(insideC); // Reference Error
console.log(insideD); // Reference Error

Yep, nested functions are actually that simple. Just define a function inside a function, there really isn’t anything “special” about it. But take extra note – Nested functions will not exist outside of their “parent function”.

 

 

A PRACTICAL NESTED FUNCTION EXAMPLE

3-table.html
<script>
function draw () {
  // (A) WE WANT TO DRAW THIS ARRAY INTO AN HTML TABLE
  var data = ["Hello", "World", "Foo", "Bar"];

  // (B) WE WILL USE THIS FUNCTION TO CREATE TABLE ROWS
  var drawRow = function(text) {
    var row = document.createElement("tr");
    var cell = document.createElement("td");
    cell.innerHTML = text;
    row.appendChild(cell);
    return row;
  };

  // (C) CREATE HTML TABLE
  var table = document.createElement("table");
  document.getElementById("table-wrap").appendChild(table);

  // (C1) HEADER
  var section = document.createElement("thead");
  section.appendChild(drawRow("RANDOM HEAD"));
  table.appendChild(section);
  // (C2) DATA
  section = document.createElement("tbody");
  for (var i of data) {
    section.appendChild(drawRow(i));
  }
  table.appendChild(section);
  // (C3) FOOTER
  section = document.createElement("tfoot");
  section.appendChild(drawRow("RANDOM FOOT"));
  table.appendChild(section);
}
window.addEventListener("load", draw);
</script>
 
<div id="table-wrap"></div>

So when do we use nested functions, and when do they make sense? The above example of creating an HTML table from an array should be pretty self-explanatory. It will kind of stupid to repeatedly use document.createElement("tr") and document.createElement("td") to create a massive table. This is where using a “temporary” drawRow() nested function to generate table rows come in handy.

 

 

EASTER EGG – FUNCTION IN FUNCTION INSIDE ANOTHER FUNCTION

4-deep-nesting.html
function functionA () {
  function functionB () {
    function functionC () {
      function functionD () {
        console.log("This is function D");
      }
      console.log("This is function C");
      functionD();
    }
    console.log("This is function B");
    functionC();
  }
  console.log("This is function A");
  functionB();
}
functionA();

This is probably something that we will never do. But just know that it is possible for us to nest functions inside a function, inside yet another function… There don’t seem to be any limit to how “deep” the nesting can go, just don’t “stack” too much and confuse yourself.

 

EXTRA

USEFUL BITS & LINKS

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

 

A QUICK SUMMARY

  • There are 4 ways to define functions in Javascript
    • Declaration – function myFunction(){}
    • Expression – var myFunction = function(){}
    • Object-Oriented – var myFunction = new Function()
    • Arrow – var myFunction = () => {}
  • Nested functions are literally just… Functions inside a function.
  • Take note – nested functions will perish outside of the parent function.
  • We can nest functions inside a function inside yet another function. But not recommended as it gets confusing.

 

 

LINKS & REFERENCES

 

CHEAT SHEET

Basic Javascript Function Nesting Example (Click to Enlarge)

 

CLOSING

WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

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