What Is a Closure in JavaScript

InstructorJohn Lindquist

Share this video with your friends

Send Tweet

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.

felikf
~ 4 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
~ 4 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.