JS Closures

eyale
2 min readDec 24, 2019

--

Here is a short explanation of JavaScript Closures. The funny thing about closures, that, if you ever wrote even one JS function you already used closures. Referring to the MDN.

In JavaScript, closures are created every time a function is created, at function creation time.

I’ll try to explain closures in a simple way. Here is my code:

Try it in console, here is the code:

const addTodo = (() => {  const todos = [];  console.info("todos:", todos);  return function add(t) {    todos.push(t);    console.info("todos:", todos);  };})();addTodo("handle Closure 1");

What is going on here?

  • We are creating constant addTodo. This constant is IIFE that returns function add.
  • Function add receives argument t — that is todo, and performs procedure — it’s just todos.push(t); and console.info(“todos:”, todos).
  • Invoking addTodo with parameter “handle Closure 1”.

The addTodo function has abilities of the add function but has no access to todos array. The add function has access to the todos array.

The important thing is to remember that JS has Static/Lexical Scope. This means that the function in JS reads the variables from where they were declared. But not from the place they were invoked.

Conclusion:

Closure — is the ability of a functions to remember the LexicalEnvironment in which they was declared.

--

--

eyale

Mobile developer, working with React Native, Swift, Flutter.