Javascript Nested Functions – Simple Examples

Welcome to a quick 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?

  • We can define functions inside a function – These are called nested functions.
  • The main reason for 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.

But just what does that mean? What practical uses are there? Let us walk through a few examples in this guide – Read on!

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

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Function Nesting Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example 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

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.

 

 

FUNCTION NESTING

All right, let us now walk through a few simple examples of nested functions.

 

1) BASIC NESTED FUNCTION

1-basic-nesting.html
// (A) DUMMY FUNCTION
function demo () {
  // (A1) NESTED FUNCTION
  function demoNest () {
    console.log("Nested called");
  }

  // (A2) PROCESS
  console.log("Demo called");
  demoNest();
}

// (B) CALL DUMMY FUNCTION
demo(); // Demo called + Nested called

// (C) NESTED FUNCTION DOES NOT EXIST OUTSIDE
demoNest(); // 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”.

 

 

2) PRACTICAL EXAMPLE – GENERATING A TABLE

2-table.html
<!-- (A) GENERATE A LIST IN HERE -->
<div id="demo"></div>
 
<script>
// (B) FUNCTION TO DRAW A TABLE
function drawtable (head, data) {
  // (B2) NESTED FUNCTION TO CREATE A ROW
  let row = function (cells) {
    let tr = document.createElement("tr");
    for (let i of cells) {
      let td = document.createElement("td");
      td.innerHTML = i;
      tr.appendChild(td);
    }
    return tr;
  };

  // (B3) CREATE TABLE
  let table = document.createElement("table");
  document.getElementById("demo").appendChild(table);

  // (B4) HEAD ROW
  table.appendChild(row(head));

  // (B5) DATA ROWS
  for (let i of data) { table.appendChild(row(i)); }
}

// (C) GO!
drawtable(
  ["Name", "Email"],
  [
    ["Job", "job@doe.com"],
    ["Joe", "joe@doe.com"],
    ["Jon", "jon@doe.com"],
    ["Joy", "joy@doe.com"]
  ]
);
</script>

This is a better practical example – It will be kind of stupid to repeatedly use document.createElement("tr") and document.createElement("td") to create a massive table. This is where using a “temporary” row() nested function to generate table rows come in handy.

 

 

3) EASTER EGG – FUNCTION IN FUNCTION INSIDE ANOTHER FUNCTION

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

 

 

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.

 

INFOGRAPHIC CHEATSHEET

Basic Javascript Function Nesting Example (Click to Enlarge)

 

LINKS & REFERENCES

 

THE END

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 *