DEV Community

Keertivaas S
Keertivaas S

Posted on

The simplest explanation I have seen for Closures in JS (Credits : roadmap.sh)

Wanted to share here, the simplest explanation that I have ever seen on the web, for the famous Closures topic. (Credits : roadmap.sh)

A closure is a function that has access to its outer function scope even after the outer function has returned. This means a closure can remember and access variables and arguments of its outer function even after the function has finished.

function outer() {
  const name = 'Roadmap';

  function inner() {
    console.log(name);
  }

  return inner;
}

const closure = outer();
closure(); // Roadmap

Enter fullscreen mode Exit fullscreen mode

In the above example, the inner function has access to the name variable of the outer function even after the outer function has returned. Therefore, the inner function forms a closure.

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

A closure is a function that has access to its outer function scope even after the outer function has returned. ...

Unfortunately, this is not correct. A closure is not a function, and ALL functions have the ability to access variables in the lexical scope in which they were defined.

Collapse
 
justanordinaryperson profile image
Keertivaas S

Thanks for your reply. I ll go through this and edit my post :)