Back to blog
Feb 2022·1 min readAI-translated

JavaScript - Closures

#javascript

A closure is created when a function accesses a variable or function outside its own scope. Essentially, a closure is a function that remembers the values that were available in the surrounding scope when it was created.

Let's explain this with an example:

function greeting(name) {
  return function() {
    console.log("Hello, " + name + "!");
  };
}

const greetJohn = greeting("John");
const greetMary = greeting("Mary");

greetJohn(); // Output: Hello, John!
greetMary(); // Output: Hello, Mary!

In this example we have a function called "greeting" that returns a closure which stores the name that was passed when "greeting" was called. We then assign a closure to each person we want to greet by storing it in variables.

When we call the stored closures, they remember the name they received when they were created and print "Hello, [name]!" accordingly.

Closures can be very useful for hiding data and providing a clean interface for other functions. They can also be very confusing, though, if you aren't aware of which variables are in scope and which aren't.

To make sure closures work correctly and don't produce unexpected results, it's important to understand scope precisely and to make sure you access and use variables and functions correctly.

NewerJavaScript - GeneratorsOlderAutomatically Rename and Copy GoPro Photos