DEV Community

delph
delph

Posted on

understanding closures in javascript

Closures

Closures are created when you define a function. A closure encompasses everything that a function can access.

var g = "G";

function functionA() {
  var a = "A";

  function functionB() {
    var b = "B";
    console.log(a, b, g);
  }

  functionB(); // prints A, B, G

  a = "Batman";
  functionB(); // prints Batman, B, G
}

functionA();

In the above example, when functionB is defined, its created closure gives it access to the global variable 'g', the variable 'a' and the variable 'b'.

Note that the closure gives a reference to the variable and not a copy of the variable. Hence, if the value of variable 'a' is changed and functionB is called again, the new value of 'a' will be printed instead of the old one.

Closure is a very important concept in functional programming paradigm. It allows a function to remember its context where it's defined.

When a function returns another function, the concept of closures becomes more relevant. The returned function has access to variables that are not in the global scope, but solely exist in its closure ie. private variables.

In the above example, the variable 'a' is considered private in the function and only accessible by functionB.

In functional programming, closures are also frequently used for partial application and currying.

alt text

Partial Application: The process of applying a function to some of its arguments. (ie. a function that takes a function with multiple parameters and returns a function with fewer parameters.)

Currying: A function that takes a function with multiple parameters as input and returns a function with exactly one parameter.

Here is another example:

function adder(a) {
  function add(b) {
    return a + b;
  }

  return add;
}
var addOne = adder(1); // a is 1, addOne has a reference to add(b)
var addTen = adder(10); // a is 10

addOne(5); // 1 (a) + 5 (b) = 6
addTen(5); // 10 (a) + 5 (b) = 15

In C and most other common languages, after a function returns, the local variables are no longer accessible because the stack-frame is destroyed.

In JavaScript, if you declare a function within another function, the inner function can remember and access variables and arguments of its outer function, even after the outer function has returned.

For further reading...

https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36
https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8
https://medium.freecodecamp.org/whats-a-javascript-closure-in-plain-english-please-6a1fc1d2ff1c

Oldest comments (1)

Collapse
 
jacqueline profile image
Jacqueline Binya

Nice intro very easy to understand.
Loved it !!!