DEV Community

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

Posted on

1

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!

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (1)

Collapse
 
harlessmark profile image
Mark Harless

Can someone give an example of closure using ES6 syntax?

👋 Kindness is contagious

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

Okay