I like to know how for of
is implemented in JS and how it works behind the scenes.
According to MDN, for of
loops over an iterable object.
My question is: For iterable objects with a sense of order (like arrays), does it respect that order when looping? Is it a requirement per the specifications? Can I count on it or should I use a for loop
if I want the elements in a particular order.
I assume that it depends on the implementation of the iterable protocol by that particular object (Arrays in this case) and for of
is just a consumer, but at the end of the day I wasn't able to find anything specific about whether order is preserved or not.
BTW, I made some tests mainly in Chrome's V8 and it seems that order is preserved when looping over arrays.
for of is implement behind the scenes using an iterator.
This is a nice short article that explains how the iterator works.
Here's an example of a custom iterator that may help you understand how it works under the hood. You need to implement a [Symbol.iterator]
method:
const iterable = {
[Symbol.iterator](){
let index = -1;
const iter = {
next(){
index++;
if(index === 0) return {value: 'This is index 0', done: false}
else if(index === 1) return {value: 'This is index 1!', done: false}
else if(index === 2) return {value: 'This is index 2!!', done: false}
else if(index === 3) return {value: 'This is index 3!!!', done: false}
return {value: 'end', done: true};
}
}
return iter;
}
}
const iterator = iterable[Symbol.iterator]();
console.log(iterator.next()); // 0
console.log(iterator.next()); // 1
console.log(iterator.next()); // 2
console.log(iterator.next()); // 3
console.log(iterator.next()); // end
As you can see here, the next
method of the Array iterator is implemented with this pseudo code: