DEV Community

Cover image for What Are Closures Anyway?
Mark Harless
Mark Harless

Posted on

What Are Closures Anyway?

During a breakup, closure is when you and your ex have accepted that your relationship with one another has come to an end. Both parties feel a sense of resolution that helps each other move on. In Javascript, closures are not that.

Let's take a look at the following function:

const breakup = (name) => {
  const saying = " needs closure.";
  return name + saying;
};

console.log(breakup("Bonnie"));
// "Bonnie needs closure."
Enter fullscreen mode Exit fullscreen mode

The function breakup() takes in a single argument and returns that argument + " needs closure.". saying is a local variable meaning it can only be used in the function where it is defined. It's inaccessible to other functions. Simple, right?

But a function can also access variables defined outside of a function:

const saying = " needs closure.";

const breakup = (name) => {
  return name + saying;
};

console.log(breakup("Bonnie"));
// "Bonnie needs closure."
Enter fullscreen mode Exit fullscreen mode

In this function, saying is now a global variable since it's defined outside of the function but still inside of its lexical scope. This is an example of a closure.

In more advanced and practical use cases, an inner function nested inside of an outer function can use closure in the same way. The inner function has access to the variables defined in the outer function. For now, just know that closures are any functions that use a variable from its parent scope!

Top comments (1)

Collapse
 
harlessmark profile image
Mark Harless

Can someone give an example of closure using ES6 syntax?