3

Consider this code.

let array = [1,2,3,4,5]

for(let elem of array) {
    console.log(elem)
}

Since here, I am not calling anything like array[Symbol.iterator]().since we can only execute function by putting parenthesis after the expression that evaluates its value. here we are just writing for(let elem of array) how does it execute a function named array[Symbol.iterator] ?

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
  • 2
    `how does it internally call symbol.iterator` - the obvious answer is ... internally ... why does it matter how it's called? – Jaromanda X Sep 29 '18 at 05:06

2 Answers2

1

You can test it simply enough by replacing [Symbol.iterator] and see what happens:

let array = [1,2,3,4,5]

array[Symbol.iterator] =  function* () {
    yield *['Larry', 'Mo', 'Curley'];
};

for(let elem of array) {
    console.log(elem)
}
Mark
  • 90,562
  • 7
  • 108
  • 148
0

Nice question, Actually the for of loop handler is mapped on for loop handler with a built-in iterator and parameters, for better understanding and using [Symbol.iterator] you can easily test it like the following code:

const iterable1 = new Object();

iterable1[Symbol.iterator] = function* () {
  yield 1;
  yield 2;
  yield 3;
  yield 4;
  yield 5;
};

const arr = [...iterable1];

for(let elem of arr) {
    console.log(elem);
}

For more information read the Docs

AmerllicA
  • 29,059
  • 15
  • 130
  • 154
  • "*Actually the for of loop handler is mapped on for loop handler with a built-in iterator and parameters,*" - could you detail that please? – Bergi Sep 29 '18 at 10:54
  • What does the code in your snippet have to do with the question? OP is asking about `for … of` loops, not array spread syntax. – Bergi Sep 29 '18 at 10:54
  • Sure dear @Bergi, he for of loop handler is mapped on for loop handler with a built-in iterator and parameters. Hence, the `for ... of` has a regular `for` inside itself. easy. – AmerllicA Sep 29 '18 at 10:58
  • You already said that. *How* do you think it is mapped? – Bergi Sep 29 '18 at 11:03
  • @Bergi, Please don't pick on my simple word, `mapped` maybe means different things for you. I explain it before. for more information read the MDN Docs. Thanks. – AmerllicA Sep 29 '18 at 11:06
  • I'm not picking on the word. I'm just missing an actual explanation. You say that `for … of` has an internal `for` loop, but never detail *how* this internal loop works. – Bergi Sep 29 '18 at 11:10