Sign in

Closures in JavaScript

“ access to outer function scope from an inner function ”

So closure is an easy concept it is just that the inner function get access to variables of the outer scope, for example

function outer(){

const a = 10;

function inner(){

const b = 10;





here in the above example, the output is 20, and the variable ‘a’ of the outer scope is getting accessed from the inner function this is because of closure

Let's take another example

function outer(){

var a = 0;

return function(){




here in this above example, what do you think the output will be in line1, line2, and line3

if you think it is going to be 0 in all three console statements then you are absolutely wrong

because the answer at line1 will be 0, line 2 is 1 and in line3 it is 2 and this is because of the closure property of javascript

  1. at line 1 the variable ‘a’ gets updated to 1 and in line 2 it is getting accessed to the updated variable ‘a’ and not to the initialized variable ‘a’
  2. In line 2 the variable ‘a’ gets updated to 2 and in line 3 it is getting accessed to the updated variable again