Javascript Closures

Closures in javascript are related to function which are catch execution state of instruction. For example inner function are capture the outer function state. Basically that is very interesting features but first let as view an example to understand the Closures logic.

function init(info){
	//inner function
	function change(){
		//Access outer function variable
		//Holding the variable state
		return ++info;
	}
	return change;
}

data=init(10);
console.log(data());
console.log(data());
console.log(data());

In this example within the init() method are define inner change() method. So inner method change() is capable to use outer function variable. And init() method are returning the reference of inner method change(). So imagin that using of this reference we can execute inner function at any time.

Closures Function example
11
12
13

Let's see an another example in closure function. In this time outer function returns an anonymous function reference.

//Return a Closures method reference
function setNumber(number){
	//return a function
	return function(){
		//inner method
		number=number+1; 
 		var status=1;
		do{
			status=1;
			//Check prime number
			for (var i = 2; i <= number/2; i++) {
				if(number%i==0){
					status=0;
					break;
				}
			}
			if(status!=1){
				//when number is not prime then
				number+=1; //check next number
			}
		}while(status==0);

		return number;
	}
}

var primeSetA=setNumber(10);
var primeSetB=setNumber(100);

console.log(primeSetA());

console.log(primeSetB());

console.log(primeSetA());

console.log(primeSetB());
Return Closures by method
11
101
13
103


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved