Closures in Javascript.

A closure is formed for the inner functions to access the variables or functions written outside the function.

A closure is created everytime a function is created.

Example

function start() {
  let value = 10;
  function processing() {
    console.log(value); 
  }
  return processing;
}
const response = start();
response(); // 10

When start function is executed it returns function which can be executed as show in example 'response()', when function is executed it prints 10. Interesting thing to note here is that even when value that is printed was not in the processing function's scope it was still able to access its value even after execution of its outer function is finished.

This is only possible when funtion when declared stores the references of its outer enviroment(lexical environment) forming a closure


Note: When importing same function over different modules values from the module is shared.

// filename - sum.js

export let value = 10;

export const incrementBy1 = () => {
  value = value + 1;
};

sum.js is imported in showValues.js.

To check the increased value from sum.js created a function getValue.

// filename - showValues.js

import { value } from "./sum.js";

export const getValue = () => value;


Value is stored in sum.js module and displayed by showValues.js module
import { incrementBy1 } from "./sum.js";
import { getValue } from "./showValues.js";

console.log(getValue()); // 10
incrementBy1();
incrementBy1();
console.log(getValue()); // 12