Open In App

JavaScript Symbol iterator Property

Last Updated : 19 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads