Wednesday, December 20, 2017

JavaScript closure function

closure function is also known as inner function.

A closure is an inner function that has access to the outer function’s variables. The closure function has three scope chains, it has access to its own scope, it has access to the outer function’s variables, and it has access to the global variables.

You create a closure function by using a function inside another function.

Ex:

function sayWelcome(name) {
  var text = 'Welcome to  ' + name;
  var say = function() {
  console.log(text);
  };
  say();
}
sayWelcome('laxman');

from above example say the function is an inner function of sayWelcome. so say function only accessible from sayWelcome function.

you can not call say function form outer side of sayWelcome function.

Closures are most use full when you want to run all functions as asynchronous, non-blocking architecture and it also frequently used in jQuery and just about every piece of JavaScript code.


You can also create closure function without the name.

Ex : 

function sayWelcome(name) {
  var text = 'Welcome to  ' + name;
  (function() {
  console.log(text);
  })();
}
sayWelcome('laxman');

above example also give the same output.

sometimes when many inner loops running asynchronous, at that time closure function is very important to manage it properly.

No comments:

Post a Comment