Skip to content

Commit 3f433cc

Browse files
committed
JS
did closure js
1 parent f01e759 commit 3f433cc

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

‎assignments/closure.js‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,45 @@
11
// ==== Challenge 1: Write your own closure ====
22
// Write a simple closure of your own creation. Keep it simple!
33

4+
let myName = "Josh";
5+
6+
function sayHello() {
7+
let example = 'jim';
8+
return `Hello ${myName}`;
9+
}
10+
11+
console.log(sayHello());
12+
console.log(example);
413

514
// ==== Challenge 2: Create a counter function ====
615
const counter = () => {
16+
let count = 0;
17+
return () => (++count);
718
// Return a function that when invoked increments and returns a counter variable.
819
};
920
// Example usage: const newCounter = counter();
1021
// newCounter(); // 1
1122
// newCounter(); // 2
23+
const newCounter = counter ();
24+
newCounter() // 1
25+
newCounter() // 2
26+
newCounter() //3
1227

1328

1429
// ==== Challenge 3: Create a counter function with an object that can increment and decrement ====
1530
const counterFactory = () => {
31+
let count = 0;
32+
return {
33+
increment: () => (++count),
34+
decrement: () => (--count),
35+
36+
};
1637
// Return an object that has two methods called `increment` and `decrement`.
1738
// `increment` should increment a counter variable in closure scope and return it.
1839
// `decrement` should decrement the counter variable and return it.
1940
};
41+
42+
const newCounterFactory = counterFactory();
43+
newCounterFactory.increment(); // 1
44+
newCounterFactory.decrement(); // 0
45+
newCounterFactory.decrement(); // -1

0 commit comments

Comments
 (0)