Content-Length: 319424 | pFad | http://github.com/lgope/JavaScript/commit/b77b5af004fadeea152795e9c430d1adc23c3c0e

6A closure question and solution · lgope/JavaScript@b77b5af · GitHub
Skip to content

Commit b77b5af

Browse files
committed
closure question and solution
1 parent 20dfde4 commit b77b5af

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Interview-Questions/output.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,3 +185,44 @@ function runWhileLoopForNSeconds(sec) {
185185
now = Date.now();
186186
}
187187
}
188+
189+
// Write a function where suppose you want to use a variable for counting something, and you want this counter to be available to all functions.
190+
191+
// Initiate counter
192+
let counter = 0;
193+
194+
// Function to increment counter
195+
function add() {
196+
counter += 1;
197+
}
198+
199+
// Call add() 3 times
200+
add();
201+
add();
202+
add();
203+
204+
// The counter should now be 3
205+
206+
// Solve
207+
const add = (function () {
208+
let counter = 0;
209+
return function () {
210+
counter += 1;
211+
return counter;
212+
};
213+
})();
214+
215+
add();
216+
add();
217+
add(); // the counter is now 3
218+
219+
// Explained
220+
// The variable add is assigned to the return value of a self-invoking function.
221+
222+
// The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.
223+
224+
// This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.
225+
226+
// This is called a JavaScript closure. It makes it possible for a function to have "private" variables.
227+
228+
// The counter is protected by the scope of the anonymous function, and can only be changed using the add function.

0 commit comments

Comments
 (0)








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/lgope/JavaScript/commit/b77b5af004fadeea152795e9c430d1adc23c3c0e

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy