Simplifying Closures in JS!

Krantibrid
2 min readSep 18, 2024

--

Closure is a javascript function that has access to its own scope, outer function’s scope and global scope even after the outer function has completed its execution. Variables

How closure works?

When a function is defined inside another function, it forms the closure. The inner variable “closes” over the variables from the outer function meaning it remembers the variables even when it is called outside its original scope.

Uses of closure

  1. Data Privacy: Closures can be used to create private variables.
function createCounter() {
let count = 0; // Private variable

return {
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
},
getCount: function() {
return count;
}
};
}

const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount()); // 2

Explanation of Private Variables

  1. Scope: The variable count is declared inside the createCounter function. Because of JavaScript’s lexical scoping rules, it is only accessible within createCounter and the inner functions that are returned.
  2. Encapsulation: The inner functions (increment, decrement, and getCount) can access and manipulate count, but there’s no way to access count directly from outside the createCounter function. This means that count is effectively "private" and “protected” from outside interference, which can help prevent bugs and maintain integrity.
  3. Controlled Access: The only way to interact with count is through the methods provided in the returned object. This encapsulation ensures that the internal state can only be modified through controlled means.

What can a closure store?

In JavaScript, a closure can store various types of data, as it captures the entire lexical scope in which it was created. Here’s what you can store as a closure:

1. Variables
Any variable (primitive types, objects, arrays) declared in the outer function’s scope can be accessed and modified.
Eg: count in the above example

2. Functions
Functions can be stored in closures, allowing you to create higher-order functions or factory functions.

function greet(greeting) {
return function(name) {
return `${greeting}, ${name}!`; // Captured variable
};
}

const sayHello = greet('Hello');
console.log(sayHello('Alice')); // "Hello, Alice!"

Summary ✨

In summary, closures are a powerful feature in JavaScript that allows functions to remember their lexical scope, enabling data encapsulation and creating private variables. Closures can store any data type available in the JavaScript scope, including variables, functions, objects, and arrays. They are widely used in various programming patterns and techniques.

--

--

No responses yet