1

I tried to print an array generated by yield and somehow if I use for...in statement it creates an array of strings while using regular for loop its working properly.
Why is that happens?

function *hello1(elements) {
    for(var el in  elements) yield el;
}
function *hello2(elements) {
    for(var i=0;i<elements.length;i++) yield elements[i];
}

var elements = [1,2,3];
console.log(elements);
console.log([...hello1(elements)]);
console.log([...hello2(elements)]);
ATP
  • 2,939
  • 4
  • 13
  • 34

2 Answers2

2

For getting the elements, you need to take for ... of statement.

The for ... in statement iterates the keys (without symbols) of the object and returns strings.

function* hello1(elements) {
    for (var el of elements) yield el;
}

var elements = [1, 2, 3];

console.log([...hello1(elements)]);

An even shorter approach returns just the array as iterable with yield* expression.

function* hello1(elements) {
    yield* elements;
}

var elements = [1, 2, 3];

console.log([...hello1(elements)]);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You meant to use for...of, not for...in which is for iterating over the enumerable keys of a target object. You can also use yield* instead of for...of and yield:

function* hello1(elements) {
  for (var el of elements) yield el;
}

function* hello2(elements) {
  yield* elements;
}

var elements = [1, 2, 3];
console.log(elements);
console.log([...hello1(elements)]);
console.log([...hello2(elements)]);
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153