What is a closure?

Closure is a commonly used mechanism in JavaScript. Plainly speaking it is a concept of a function defined inside another function that remembers it’s lexical scope (and so is able to manipulate it).

How does it look

Simple example

const example = () => {
  const privateVariable = 'privateValue';

  return () => {
    console.log(privateVariable);
  };
}

const useClosure = example();
useClosure(); // logs privateValue

Steps:

  1. return a function definition inside another function
  2. save called outer function in a variable
  3. execute it to use the closure and reach hidden code

That is just one way of using closures, but the point is the same – the inner function remembers it’s lexical scope (even though it is executed outside of it).

Why are closures useful?

There are many benefits of using closures. Closures may help us avoid code collisions, keep more maintainable, more easily deployable, more secure, and more testable code. These benefits come from more easily enforceable PoLP (Principal of Least Privilege) and cleaner environment (global scope) that results from code hiding. Various patterns using closures (i.e. module) let’s us keep certain functionality and data private and reachable only to specified areas of code.

closures → hidden code → PoLP, clean environment → happy you

Closures can help you avoid repetition, you can use them for partial application (taking a function with some arguments and creating a function with less).

Example of partial application

const currySum = (sumItemOne) => {
  return (sumItemTwo) => {
    return sumItemOne + sumItemTwo;
  }
} 

const addFive = currySum(5); 
const addSix = currySum(6); 
console.log(addFive(1)); // function adds private value 5 to any argument (1 in this case) logs 6
console.log(addSix(1)); // same thing but with 6 instead of 5

Summary

Closure is a mechanism found everywhere in the JavaScript world (and outside of it) from event handlers, to module system, to many popular libraries like jQuery. It is unavoidable and crucial to understand for any JavaScript developer. Hopefully this article was fun to read and is going to help you out.

Best Wishes, Vladas Končius


Leave a Reply

Your email address will not be published.