Understanding Closures in JavaScript

Prem Parmar
2 min readAug 22, 2020

--

Before diving into closures, first of all we need to know what is closures?

Closures can be defined as inner / nested function preserving all variables and arguments of its outer functions.

Let us take some simple example of closure:

show() inner-function has access of “sirName” and “name” which is closures. Here below, i attached output of console.dir(show) and you can see that in [[Scopes]] of that function has key Closure which contains value of “name” and “sirName”.

In interview, sometimes they don’t consider this simple example so we have to return function show() from the person function and call it from outside. you can also check console.dir() and you get same result which i mentioned ahead.

In a nutshell, Closure is accessing or preserving of outer function’s variable and arguments in Inner function.

--

--

Prem Parmar
Prem Parmar

Written by Prem Parmar

Software Engineer, having 3 years of experience in Ecommerce / HCM domain Product based company.

No responses yet