File tree Expand file tree Collapse file tree 1 file changed +29
-1
lines changed
Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Original file line number Diff line number Diff line change 11// ==== Challenge 1: Write your own closure ====
22// Write a simple closure of your own creation. Keep it simple!
3+ const closure = ( ) => {
4+ let myName = 'Erin' ;
5+ console . log ( `My name is ${ myName } .` ) ;
6+ const favoriteBand = ( ) => {
7+ let band = 'Queen' ;
8+ console . log ( `My name is ${ myName } , and my favorite band is ${ band } .` ) ;
9+ } ;
10+ return favoriteBand ( ) ;
11+ } ;
12+ closure ( ) ;
313
414
515// ==== Challenge 2: Create a counter function ====
616const counter = ( ) => {
7- // Return a function that when invoked increments and returns a counter variable.
17+ var counterVar = 0 ;
18+ function incrementCounter ( ) {
19+ return function ( ) {
20+ counterVar ++ ;
21+ return counterVar ;
22+ } ;
23+ }
24+ return incrementCounter ( ) ;
825} ;
26+ const newCounter = counter ( 0 ) ;
27+ newCounter ( ) ;
928// Example usage: const newCounter = counter();
1029// newCounter(); // 1
1130// newCounter(); // 2
1231
1332
1433// ==== Challenge 3: Create a counter function with an object that can increment and decrement ====
1534const counterFactory = ( ) => {
35+ let counterVar = 0 ;
36+ const increment = ( ) => {
37+ counterVar += 1 ;
38+ increment ( ) ;
39+ return counterVar ;
40+ } ;
41+ const decrement
42+ return increment ( ) ;
43+
1644 // Return an object that has two methods called `increment` and `decrement`.
1745 // `increment` should increment a counter variable in closure scope and return it.
1846 // `decrement` should decrement the counter variable and return it.
You can’t perform that action at this time.
0 commit comments