Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when we write for..of loop how does it internally call symbol.iterator [duplicate]

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] ?

like image 710
Chetan Tomar Avatar asked Dec 28 '25 22:12

Chetan Tomar


1 Answers

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)
}
like image 174
Mark Avatar answered Dec 30 '25 10:12

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!