File tree 1 file changed +41
-0
lines changed 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -185,3 +185,44 @@ function runWhileLoopForNSeconds(sec) {
185
185
now = Date . now ( ) ;
186
186
}
187
187
}
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.
You can’t perform that action at this time.
0 commit comments