DEV Community

Cover image for Closures in JavaScript
baijanathTharu
baijanathTharu

Posted on

Closures in JavaScript

Closures

  • Closures are the functions defined inside a function.
  • For example: In the code below, innerFunction is a closure.
function outerFunction() {
  function innerFunction() {
    let text = "I am a closure";
    return text;
  }
  let text = "I am an outer function";
  return text;
}

Making closure accessible from outside the functional scope

  • Invoking outerFunction will return a text "I am an outer function".
  • We can invoke the innerFunction inside the outerFunction.
  • But how can we invoke the innerFunction from the global scope?
  • In order to do so, instead of returning a text in outerFunction, we can return the innerFunction itself as below:
function outerFunction() {
  function innerFunction() {
    let text = "I am a closure";
    return text;
  }
  return innerFunction;
}
  • Now we have access to the innerFunction.
// invoking outerFunction to get access to _innerFunction_
console.log(outerFunction()); // returns [Function: innerFunction]
// This shows we have access to the _innerFunction_
  • If we invoke outerFunction, with two parenthesis, we can see the variable text defined inside innerFunction returned as below:
console.log(outerFunction()()); // return "I am a closure"

  • We can have closures penetrating deep inside a function.
  • For example:
function addition(num1) {
  var addition2 = function (num2) {
    var addition3 = function (num3) {
      return num1 + num2 + num3;
    };
    return addition3;
  };
  return addition2;
}

console.log("3 + 3 + 3 = ", addition(3)(3)(3)); // returns 9
console.log("4 + 5 + 6 = ", addition(4)(5)(6)); // return 15

Top comments (2)

Collapse
 
baijanaththaru profile image
baijanathTharu

Closures are used in event handlers, callback functions and for protecting data which shouldn't be accessible in global scope.

Collapse
 
bias profile image
Tobias Nickel

the last example.is currying, I thing today peoplebwould write that more as

const addition = (num1) => (num3) => (num3) => num1 + num2 + num3;

I think the ramdalib and reduz take heavy use of this sytax.

I am glad that closures don't play such a big role today anymore, now that we have asyc/await.