DEV Community

Cover image for JavaScript Closures: Understanding the Power Behind the Scenes 🧐
Matheus Costa
Matheus Costa

Posted on • Edited on

JavaScript Closures: Understanding the Power Behind the Scenes 🧐

Closures are one of the most powerful features of JavaScript, but they can also be a source of confusion for many developers. In a nutshell, a closure is a function that remembers values in the enclosing scope, even after the parent function has closed.

This allows us to create functions that have a private scope, and to maintain state and encapsulation in our code. Closures have some pretty neat use cases such as implementing private variables and methods, event handling, async operations. They're also fundamental to functional programming, used for implementing higher-order functions, currying and can also be used for performance optimization techniques such as memoization.

Creating OOP with closures:

function createPerson(name, age) {
  let person = { name, age };

  return {
    getName: function() {
      return person.name;
    },
    getAge: function() {
      return person.age;
    },
    setName: function(newName) {
      person.name = newName;
    },
    setAge: function(newAge) {
      person.age = newAge;
    }
  };
}

const person = createPerson("John Doe", 30);
console.log(person.getName()); // John Doe
console.log(person.getAge()); // 30
person.setName("Jane Doe");
person.setAge(32);
console.log(person.getName()); // Jane Doe
console.log(person.getAge()); // 32
Enter fullscreen mode Exit fullscreen mode

In this example, we use a closure to create a createPerson function that returns an object with private state (the person object) and public methods for accessing and modifying that state (getName, getAge, setName, and setAge). This allows us to create objects with a defined interface and private state, just like in traditional OOP.

Closures provide a powerful and flexible way to implement many things in JavaScript, and they are widely used in many libraries and frameworks. If you're not already familiar with closures, I highly recommend taking the time to learn and understand this important concept. πŸ’‘

Top comments (9)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

a closure is a function that remembers values in the enclosing scope

This isn't correct - if it were, then there would be no point having the separate words 'closure' and 'function', since ALL functions remember values in the scope in which they were created.

From MDN (empasis mine):

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

It's a subtle difference in meaning, but closure β‰  function.

Collapse
 
costamatheus97 profile image
Matheus Costa

Its not correct taken out of the entire text lol

Collapse
 
costamatheus97 profile image
Matheus Costa

β€œIn a nutshell, a closure is a function that remembers values in the enclosing scope even if they are not present in memory.”

Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Yeah, it's tricky to word... but wording it like that essentially makes it seem like either: closures and functions are the same thing, or that a closure is a special kind of function - neither of which is true. These are confusions that I see a lot from interview candidates and junior devs. I think it's important to try to be clear.

Also, if the variables can be 'remembered', then they are still present in memory - your function isn't psychic! πŸ™‚

Thread Thread
 
costamatheus97 profile image
Matheus Costa • Edited

Yes, that made no sense lol. I’ll fix it.

But still, closures are functions, but that doesn’t imply that functions and closures are the same, or that all functions are closures. By w3 definition:

A closure is a function having access to the parent scope, even after the parent function has closed.

Thread Thread
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

A function and a closure are two different things.

Wikipedia:

In programming languages, a closure, also lexical closure or function closure, is a technique for implementing lexically scoped name binding in a language with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment.[1] The environment is a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b] Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.

Collapse
 
naucode profile image
Al - Naucode

Great article, you got my follow, keep writing!

Collapse
 
bcostaaa01 profile image
Bruno • Edited

Your explanation sounds somehow confusing when you say a closure is a function. It is a function object that remembers their surrounding state, even if you invoke them outside their scope.

Also, might be me, but saying closures are OOP is not that correct. It can be used in an OOP context, yes, but not a concept of OOP. They are a key concept of functional programming. It’s worth checking this out:

And another example:

function greet(greeting) {
  return function(name) {
    console.log(`${greeting}, ${name}`);
  };
}

const sayHello = greet("Hello");
sayHello("Matheus"); // "Hello, Matheus"
Enter fullscreen mode Exit fullscreen mode

Here, what’s happening is that the greet function takes a greeting argument and returns an anonymous function which takes name as an argument. The returned anonymous function logs a string of greeting and name arguments combined.

Collapse
 
costamatheus97 profile image
Matheus Costa

But closures are not OOP, they can be used to implement OOP and features like private methods and variables. Which weren’t a possibility in class until very recently.

And a closure is a function, but not all functions are closures. By w3 definition:

A closure is a function having access to the parent scope, even after the parent function has closed.