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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay