Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Closure Example


	 function Counter() {
    var counter = 0;
alert("XXXXX");
function increaseCounter()
{
return counter +=1;
} 

return increaseCounter;
}

/***/
const counter = new Counter();
console.log(counter());
console.log(counter());


/*note that alert("XXXX") only executes once*/
/*think of counter() = new Counter() declaration as storing the value of ONE Counter function execution and 
the remaining times you use counter(), you reexecute only the returned function*/
/*use counter() instead of Counter() if you want alert("XXXX") to execute only once AND for you to be able to return an actual value otherwise you only console.log a function and alert executes multiple times*/
Source by developer.mozilla.org #
 
PREVIOUS NEXT
Tagged: #Closure #Example
ADD COMMENT
Topic
Name
8+8 =