What Is a Closure in JavaScript

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

When working with closures you'll often hear the words "capture", "wrap", or "enclose". The entire idea behind a closure is to take a variable outside of the function and use that variable inside the function. A closure enables patterns for passing around functions that can manage buffers, caches, and values that can travel with the function.

John Lindquist: [0:00] Closure() is a function that accesses stuff not defined inside of it. If I defined a name up here of John and then console.logged out a name in here and called the closure, that would log out John. If I reassigned name to Mindy and then called the closure again, it logs out John then Mindy.

[0:27] If I set this to i and set this at , and then I logged out i++, every time I called the closure, we'll call it three times, you'll see, I'll zoom in, , 1, and 2. The huge difference here is if I was defined inside the closure and I hit Save, you'd see , , and because this is inside of the scope of this function and is recreated each time the function is called.

[0:59] It's the ability of functions to capture anything outside of the function and use that value each time the function is called, that make closure special.

felikf
felikf
~ 3 years ago

Isn't this just accessing a global variable? Don't we need an enclosing function to create a closure?

function outer(i) {
  let closureVar = '1';

  return function inner() {
    console.log(closureVar + i);
  }
}

outer(1)();
Creeland Provinsal
Creeland Provinsal
~ 3 years ago

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

 A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).

So this is still a valid example of a closure since it is a function that is accessing the state of its surrounding environment.

Markdown supported.
Become a member to join the discussionEnroll Today