Closure

Simple Closure example to show how Inner and Outer functions work together

by Thomas Orthbandt

JavaScript

var globalVar = "xyz"; // Global Variable

(function outerFunc(outerArg) { // Outer Argument
  var outerVar = 'a'; // Outer Variable

  (function innerFunc(innerArg) { // Inner Argument
    var innerVar = 'b'; // Inner Variable

    document.write(
      "<p style='color:black'>" + "globalVar = " + globalVar + "</p>" +
      "<p style='color:black'>" + "outerArg = " + outerArg + "</p>" +
      "<p style='color:black'>" + "outerVar = " + outerVar + "</p>" +
      "<p style='color:black'>" + "innerArg = " + innerArg + "</p>" +
      "<p style='color:black'>" + "innerVar = " + innerVar + "</p>");

  })(456); // Inner Function as `Immediately Invoked Function Expression` (IIFE)
})(123); // Outer Function as `Immediately Invoked Function Expression` (IIFE)