Internals of Javascript Iterables and Array-Like objects

Deep dive into Javascript Iterables and Array-like objects. Learn about @@Iterator and mechanisms of how Array & other iterables loop through data.

Internals of Javascript Iterables and Array-Like objects

Hi,

A few months back, I started learning Javascript and its crucial concepts; coming from a Java background, learning Javascript was not very tough for me, to be honest. I started with data types, Variables, Strings, and Arrays, etc.
There are many many courses out there on Udemy, and; you will also agree, how alluring they are structured. So I took a course and started my JS journey. I was totally blown away by how DOM works, how powerfully we can edit and manipulate web elements. JavaScript being 'weakly-typed'; I became a fan of it.

But at the same time, watching people talking and creating great projects using React, there were moments, I was getting uncontrollable temptation to start learning React right away. And happened what! I started looking about React, React components, JSX...etc.

But deep down, a sense of incompleteness in Javascript was pushing me back again and again to Javascript. And then (one day I finally) decided to switch back to Javascript, and I think my actual JS learning started after then only.
In that journey, I got to know about many amazingly great articles and websites, for eg; JavaScript.info, 30-days JS Challenge to name a few.

In my whole learning, I noticed many crucial JS concepts people don't talk about much and, if they talk, it sounds very vague. I feel those are some concepts that make Javascript beautifully exceptional. So, I decided to gather more information about those concepts and list them down.
In this and upcoming blogs under this series, we'll discuss and play with such cruical and less talked Javascript concepts.

And, today we'll talk about one of my favourites Iterables and Array-like Objects.

Iterables and Array-like Objects

Iterating over Arrays and Strings is not very uncommon in any programming language. But do you ever thought about how Arrays or any other collections iterate over the list in JavaScript? To answer this question in one Sentence, "These Collections (Arrays, Strings, Map, Set, etc.) implement Iterable Protocol within themselves to enable for...of iteration over their list items."

Any object or collection which is iterable, must follow the Iterable protocol, i.e., the object must implement the @@iterator [Symbol.iterator] method which conclusively returns an Iterator object consisting of at least a next() method which in-turn returns an object with current value and iteration status.

Let's see an example; we know objects are generally non-iterable with for...of loop, obviously because objects do not implement @@iterator method. In the below example, we'll manually implement the @@iterator method within an object and will see how things work.

//alphalist is initially non-iterable with for...of.
let alphaList = {
  A: "Apple",
  B: "Ball",
  C: "Cat",
  D: "Dog",
  [Symbol.iterator]: iteratorFunc,
  // Implementing @@Iterator method.
  // This method will make this object Iterable.
};

//returns Object with next() function.
function iteratorFunc() {
  return {
    objValues: Object.values(this),
    lastKeyIndex: Object.values(this).length - 1,
    currentKeyIndex: 0,
    next() {
      if (this.currentKeyIndex <= this.lastKeyIndex) {
        return { value: this.objValues[this.currentKeyIndex++], done: false };
        //returns current value and, Iteration status, done: false/true
        //false -----> Iteration Incomplete;
        //true -----> Iteration Completed, no more data.
      } else {
        return { value: null, done: true };
      }
    },
  };
}

//for...of now working with alphaList object
for (let val of alphaList) {
  console.log(val);
  // "Apple", "Ball", "Cat", "Dog"
}

And, this is how for...of internally iterate over the elements. It executes the @@iterator method and calls the next() method again and again until the done key-value results in true.

image.png

A good understanding of Iterables helps to easily understand the difference between Iterables, Array, and Array-like objects.
Array-likes are objects that have indexes and length, as like arrays, but may or may not be Iterable. For eg.; Strings are array-like and Iterable.

But, the below example is Array-like but non-Iterable.

let arrayLike = { // has indexes and length => array-like
  0: "Hello",
  1: "World",
  length: 2
};

// Error (no Symbol.iterator)
for (let item of arrayLike) {}

//Note: example taken from Javascript.info

You may ask, what is the difference between Array and Array-like, then?
The Array and Array-like both have indexes and length properties, but please note the arrays have some extra methods like push(), pop(), etc. which majorly differentiate the arrays from array-like objects.

Conclusion

  • Iterables are objects that implement the @@iterator method, and may or may not be Array-like.
  • Arrays have Index and length property and are Iterable.
  • Array-Like objects also have indexes and length property, but may or may not be Iterable.

So, that's all for Iterables, Arrays, and Array-Like Objects. I hope you enjoyed reading about these concepts.
I strongly recommend checking the articles on Iterables and Array-like objects on MDN and JavaScript.info to learn more about it.

Until then, Keep thriving!
Stay Safe!

To be Continued... Up next in the Series, Symbols.