Skip to content

Commit d9ffd03

Browse files
committed
started closure
1 parent ae6e7f6 commit d9ffd03

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

assignments/closure.js

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,46 @@
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 ====
616
const 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 ====
1534
const 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.

0 commit comments

Comments
 (0)