> For the complete documentation index, see [llms.txt](https://april.gitbook.io/learning-js/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://april.gitbook.io/learning-js/chapter-12..md).

# CHAPTER 12. 이터레이터와 제너레이터

* ES6에 도입된 개념&#x20;
* 제너레이터 : 이터레이터에 의존하는 개념
* 이터레이터 : 책갈피와 비슷함&#x20;
  * ex) 배열 - 이터러블 객체

### 이터레이터의 특징

#### 1) next() 메소드

* 진행할 것이 있으면 done : false
* 진행할 것이 없으면 value는 undefined, done은 true
* 계속 next로 호출할 수 있으나 끝까지 진행하면 뒤로 돌어가서 다른 데이터를 제공할 수는 없음

```javascript
  const book = [
    "Twinkle, twinkle, little star",
    "How I wonder what you are",
    "Up above the world so high",
    "Like a diamond in the sky",
    "Twinkle, twinkle little star",
    "How I wonder what you are"
  ];

  const it = book.values(); // 이터레이터 생성

  console.log(it.next()); // {value: "Twinkle, twinkle, little star", done: false}
  console.log(it.next()); // {value: "How I wonder what you are", done: false}
  console.log(it.next()); // {value: "Up above the world so high", done: false}
  console.log(it.next()); // {value: "Like a diamond in the sky", done: false}
  console.log(it.next()); // {value: "Twinkle, twinkle little star", done: false}
  console.log(it.next()); // {value: "How I wonder what you are", done: false}
  console.log(it.next()); // {value: undefined, done: true}
  console.log(it.next()); // {value: undefined, done: true}
  console.log(it.next()); // {value: undefined, done: true}
  console.log(it.next()); // {value: undefined, done: true}
```

#### 2) 독립적

* 새 이터레이터를 만들 때마다 처음에서 시작
* 각각 다른 쇼로르 가리키는 이터레이터 여러 개를 동시에 사용할 수 있음

```javascript
  const book = [
    "Twinkle, twinkle, little star",
    "How I wonder what you are",
    "Up above the world so high",
    "Like a diamond in the sky",
    "Twinkle, twinkle little star",
    "How I wonder what you are"
  ];

  // 이터레이터 생성
  const it1 = book.values();
  const it2 = book.values();

  // it1 으로 두 페이지 읽음
  console.log(it1.next()); // {value: "Twinkle, twinkle, little star", done: false}
  console.log(it1.next()); // {value: "How I wonder what you are", done: false}

  // it2 로 한 페이지 읽음
  console.log(it2.next()); // {value: "Twinkle, twinkle, little star", done: false}

  // it1 으로 한 페이지 더 읽음
  console.log(it1.next()); // {value: "Up above the world so high", done: false}
```
