Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Symbol iterator Property

JavaScript Symbol iterator Property

It is an object of Iterables which is also a kind of generalized arrays. Iterables that make any object easier to use in a for..of the loop. We know that arrays are iterative in nature but other than that, there are also several objects which are used for the iterative purpose. Suppose if any object which is not an array but does possess a group of the list, set, etc then for..of can be used to iterate it.

We use for..of loop to represent a range object of any interval. It decides the range in which the for..of the loop will work and iterate the loop.

We will use a method Symbol.iterator (an in-built method in JavaScript) to iterate the range object which is mentioned above. The steps in which this method works:

  1. Once for..of loop starts it checks the error first, if it is not found then it accesses the method and the object with the method.
  2. After that for..of loop will run over the object.
  3. To take the next upcoming value, it calls the next() method for that output object.
  4. The values returned will be of the form {done: Boolean, value: any}. When done=true is returned then the loop will be considered as the complete one.

Syntax:

[Symbol.iterator]

Features:

  • The range will not have the next() method on its own.
  • When we call to the range[Symbol.iterator](), an iterator is formed and the method next() will generate the value for further iterations.

Example:

Javascript




let range = {
  from: 2,
  to: 7
};
  
range[Symbol.iterator] = function() {
  
  return {
    now: this.from,
    end: this.to,
    next() {
      if (this.now <= this.end) {
        return { done: false, value: this.now++ };
      } else {
        return { done: true };
      }
    }
  };
};
  
for (let i of range) {
  console.log(i); 
}


Output:

2
3
4
5
6
7

Supported Browsers: The browsers supported by Symbol iterator property are listed below:

  • Google Chrome 51
  • Firefox 50
  • Edge 15
  • Opera
  • Apple Safari

We have a complete list of Javascript symbols’ properties and methods, to check those please go through the Javascript Symbol Complete Reference article.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments