Easy Way to Grasp JavaScript Closures

Taha El Bouffi
Nerd For Tech
Published in
2 min readFeb 18, 2021

--

What is a closure?

In few words: A closure is the ability of a function to access its outer scope.

In JavaScript, every time a function is created, a closure is associated to it. And thanks to closure, JavaScript inner functions has access to:

  • Outer function’s variables
  • Global variables

The function sayHellohas a closure the let it access the global scope variable myName. Also, if myName changes, sayHellowill print the new value that this global variable has taken.

Most Funny Part of Closures

In most cases we think about JavaScript closures as functions inside other functions, as shown in the example.

  • The function outerFct returns the function innerFct
  • First we call outerFct('ging')and pass it to myFct variable
  • Then we call myFct('gon') that logs hi inner variable gon and hi outer variable ging

So how it is possible that myFct('gon') could log hi outer variable ging ?

It’s closure

When we call const myFct = outerFct('ging'); closure let our inner function that is inside the outer function outerFct which has the argument 'ging' to save it as an outer variable that it will remembre all the time of execution.

So when we call the function myFct('gon'), we are in fact calling the inner function that still has in its closure the value of outerVar which is ging.

Note that we have the same behavior if we directly call:

outer('ging')('gon');           | results:
| hi inner variable gon
| hi outer variable ging

To conclude, whenever a function is created, then a closure of this function is created too. This closure has access to three kind of scopes:

  • Global scope
  • Outer function scope from where the inner function is created
  • Inner Scope of the inner function

--

--

Taha El Bouffi
Nerd For Tech

Full Stack JavaScript Developer Experienced in NodeJS, Express, MongoDB, React, etc.