JavaScript Closure

In JavaScript, closures are created every time a function is created, at function creation time.
 
Closure
means that an inner function always have access to the variables and
parameters of its outer function even after the outer function has
returned. This is not common with other programming languages.

Sample Code:
function simpleFunc() {

  let strName = ‘Magulan’;
 
  function showName() {
 
    alert( strName);
    
  }
 
  return showName;
 
}



var myFunc = simpleFunc();
myFunc();//alerts Magulan which is outer function variable.

It
shouldn’t alert Magulan since the strName is a variable from outer
function. It is alerting because of closures. 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 the closure was created.

Another Sample Code:
function add( x ) {

  return function( y ) {
 
    return x + y;
    
  };
 
}

let obj = add( 2 );
alert( obj( 3 ) );//alerts 5

Leave a Reply