1

From the output of following snippets, I can conclude the following. But not sure if they are correct or not.

i) for...of can be used both for iterable and iterator
ii)for...in can only used for iterable and not for iterator

    var array1 = ['a', 'b', 'c'];
    var iterator = array1.keys(); 

    for (let key of iterator) {
      console.log(key); // 0 1 2
    }
    for (let value of array1) {
      console.log(value); // 'a' 'b' 'c'
    }
    for (var index in array1) {
      console.log(array1[index]); // 'a' 'b' 'c'
    }
    for (var key in iterator) {
      console.log(key); // `Not executed`
    }
Prem
  • 5,685
  • 15
  • 52
  • 95
  • FYI - `array1.keys()` is `{}` – Rahul Desai Apr 19 '18 at 19:58
  • Or, you could just read the docs - [for ... in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in), [for ... of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of). Also relevant but immediately linked there, [iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) – ASDFGerte Apr 19 '18 at 20:00
  • `for … in` can only be used on *enumerable* objects. It has nothing to do with iterators/iterables. (It's just that in your example, the array has some enumerable properties while the iterator has not. In any case, [don't use `for…in` enumerations on arrays!](https://stackoverflow.com/q/500504/1048572)) – Bergi Apr 19 '18 at 20:05
  • Notice that all iterators are iterable by simply returning themselves from `[Symbol.iterator]()`. `for of` always works on iterables. – Bergi Apr 19 '18 at 20:06

0 Answers0