DEV Community

Itamar Tati
Itamar Tati

Posted on

2

What Are Closures in JavaScript? (1 Minute Guide)

What Are Closures in JavaScript?

Closures are a fundamental concept in JavaScript that can seem tricky but are incredibly powerful. Here's a quick guide to understanding them.

What is a Closure?

A closure is created when a function "remembers" the variables from its lexical scope, even after that scope has exited.

Example:

function outerFunction(outerVariable) {  
  return function innerFunction(innerVariable) {  
    console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);  
  };  
}  

const myClosure = outerFunction("Hello");  
myClosure("World");  
// Output: Outer: Hello, Inner: World
Enter fullscreen mode Exit fullscreen mode

Here, innerFunction has access to outerVariable from outerFunction's scope, even after outerFunction has finished executing.

Why Are Closures Useful?

Data Privacy: Create private variables.

function counter() {  
  let count = 0;  
  return function () {  
    count++;  
    return count;  
  };  
}  
const myCounter = counter();  
console.log(myCounter()); // 1
console.log(myCounter()); // 2  
Enter fullscreen mode Exit fullscreen mode

Partial Application: Pre-fill function arguments.

function multiplyBy(multiplier) {  
  return function (number) {  
    return number * multiplier;  
  };  
}  
const double = multiplyBy(2);  
console.log(double(5)); // 10  
Enter fullscreen mode Exit fullscreen mode

Conclusion

Closures let functions remember their environment. They’re great for private variables, partial application, and many other advanced patterns in JavaScript.

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!