A function and the lexical context in which it was declared are combined to form a closure. Specifically, it is an inner function that has access to the variables of the outside or surrounding function.

Functions that refer to independent (free) variables are called closures. The function specified in the closure, in other words, "remembers" the environment in which it was developed.

The closure has three scope chains -

  1. Own scope where variables defined between its curly brackets
  2. Outer function?s variables
  3. Global variables

Let's look at a closure concept example.

function Welcome(name) {
  var greetingInfo = function (message) {
    console.log(message + " " + name);
  };
  return greetingInfo;
}
var myFunction = Welcome("John");
myFunction("Welcome "); //Output: Welcome John
myFunction("Hello Mr."); //output: Hello Mr.John

According to the code above, even after the outer function has returned, the inner function (i.e. greetingInfo) can access the variables in the outer function scope (i.e. Welcome).


Recommended Posts

View All

Difference between Function, Method and Constructor calls in JavaScript


You are probably used to thinking about functions, methods, and class constructors as three distinct things if you are experienced with object-oriente...

10 JavaScript Tricks Every Developer Should Know


I'll show you several JavaScript tricks for optimizing your JavaScript code. Use these JavaScript tricks to optimize your JavaScript code.

Difference Between == and === in JavaScript


Learn the Difference Between == and === in JavaScript. Discover how each operator compares values and data types, and when to use them in code.

Difference between var and let in JavaScript


Learn the difference between var and let in JavaScript. Understand variable hoisting, scope, and how they affect your code's behavior. Get started now...

What is the Temporal Dead Zone in JavaScript?


The time frame in which access to the let and const declarations is prohibited is known as the Temporal Dead Zone.