DEV Community

mpbyoyo
mpbyoyo

Posted on

Trying to Understand Closures Better by Writing About Them

Closures are created between a function and a variable whenever a function is not a pure function. A pure function is any function that only relies on variables declared within the function and the parameters of the function.

Example of a pure function:

function pure(a) {
  var b = 1;
  return a + b;
}
pure(1); // -> 2

// This function only uses the argument passed in the "a"
// parameter, and the variable "b" declared in the function.
// This makes it a pure function.
Enter fullscreen mode Exit fullscreen mode

Example of a not-pure function (function with a closure):

var b = 1;
function impure(a) {
  return a + b;
}
impure(1); // -> 2

// This function is not a pure function, as it relies on the
// variable "b" which is declared outside of the function.
Enter fullscreen mode Exit fullscreen mode

In the above function "impure," a closure is created between "var b" and the place where the variable is called in the function. This closure allows that value to be accessed in real time, even if the value of the variable changes:

var b = 1;
function impure(a) {
  return a + b;
}
b = 2;
impure(1); // -> 3
Enter fullscreen mode Exit fullscreen mode

Really, a closure is just a way to dynamically store the values of variables (or other functions) for future use. This can be useful for keeping certain values alive and accessible even after a function ends:

function pure(a){
   return function impure(b) {
      console.log(a + b);
   }
}
const closureFunct = pure(1)
closureFunct(1) // -> 2
Enter fullscreen mode Exit fullscreen mode

In this example, a closure is formed between the "impure" function and the parameter "a" from the "pure" function. This closure will dynamically store the value of "a," even after the function ends.

Top comments (0)