0

Hi I was going through closure concept in JavaScript. I am finding it difficult to understand it. Can someone please help me?

function a(name) {
 return function () {
  console.log( "Hello "+ name);
 }
}
var b = a("MyName");
b();

According to closure, inner function will have access to its outer function's variables even after the execution of outer function is compeled and it's no more present in stack. Can some one please explain how inner function is able to access its variable even after execution for outer function is completed. I have tried above code and it's working as expected but I am confused?

Aniket
  • 3
  • 1
  • 7

1 Answers1

0
function a(name) {
 return function () {
  console.log( "Hello "+ name);
 }
}
var b = a("MyName");
b();

A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time that the closure was created. In this case, b is a reference to the instance of the inner function returned when a() is run. The instance of returned function maintains a reference to its lexical environment, within which the variable name exists. For this reason, when b() is invoked, the variable name remains available for use and name is passed to console.

Dij
  • 9,761
  • 4
  • 18
  • 35