---
# System prepended metadata

title: '[LC JS30] Closure 閉包'
tags: [Javascript]

---

# [LC JS30] Closure 閉包


## Day 1  Create Hello World Function

### 題目：
Write a function createHelloWorld. It should return a new function that always returns "Hello World".
### 解答：
```javascript
var createHelloWorld = function() {
    return () => "Hello World"
};
```
* 一般函式基本觀念：
    * 具名函式
    * 匿名函式(Anonymous Function)
    * 立即函式(Immidiately Invoked Function Expression)
    * Functions within Functions
    * 函式提升(Function Hoisting)
        * You can only do this if you declare functions with the `function` syntax.
    * Closure
* 箭頭函式
```javascript!
 const f = (a, b) => {
  const sum = a + b;
  return sum;
};
console.log(f(3, 4)); // 7
```

### Closure 閉包
* When a function is created, it has access to a reference to all the variables declared around it, also known as it's lexical environment. The combination of the function and its enviroment is called a closure.
```javascript!
function createAdder(a) {
  function f(b) {
    const sum = a + b;
    return sum;
  }
  return f;
}
const f = createAdder(3);
console.log(f(4)); // 7
``` 
## Day2 Counter
### 題目：
Given an integer n, return a counter function. This counter function initially returns n and then returns 1 more than the previous value every subsequent time it is called (n, n + 1, n + 2, etc).
```javascript!
/** 
 * const counter = createCounter(10)
 * counter() // 10
 * counter() // 11
 * counter() // 12
 */
```

### 解答
```javascript
var createCounter = function(n) {
    return () => n++;
};
```
#### ⭐知識點
* `createCounter(10)` 函式賦值到 `counter` 形成獨立的作用域，裡面的值 `n` 會重複累加
* `n++` 會先回傳值，再運算；`++n` 則會先運算再回傳值
  * https://ithelp.ithome.com.tw/articles/10192800


#### 🐕自己寫的初版
```javascript
var createCounter = function(n) {
    let count = 0
    return ()  => {
        count++
        return count + n - 1
    };
};
```

## Day3 CouterII
### 題目：
Write a function `createCounter`. It should accept an initial integer `init`. It should return an object with three functions.

The three functions are:

-   `increment()` increases the current value by 1 and then returns it.
-   `decrement()` reduces the current value by 1 and then returns it.
-   `reset()` sets the current value to `init` and then returns it.

```javascript
const counter = createCounter(5)
counter.increment(); // 6
counter.reset(); // 5
counter.decrement(); // 4
```


### 解答：
```javascript
var createCounter = function(init) {
    let num = init
    return {
        increment: () => ++num,
        decrement: () => --num,
        reset: () => num = init
    }
};
```

