• JavaScript Video Tutorials

JavaScript - Symbol.iterator Property



In JavaScript, a special symbol called Symbol.iterator property is used to specify a custom iterator for an object. The Symbol.iterator property is used to define the behavior of an iterator for a particular object. Iterators are objects that allow a way to access a collection of elements one at a time.

When an object has a Symbol.iterator property, it means that it can be iterated over using a for...of loop or the ... spread operator. Many of the built-in data structures in JavaScript, such as strings, arrays, maps, sets, and so on, have default iterators. This default iterator can be accessed using the Symbol.iterator property.

Syntax

Following is the syntax of JavaScript Symbol.iterator property −

[Symbol.iterator]

Parameters

This property doesn't accept any kind of parameter.

Return value

This property returns an iterator object.

Examples

Example 1

Let's look at the following example, where we are going to use the generator function that produces a sequence when iterated over in the for of loop.

<html>
   <body>
      <script>
         const x = {
            [Symbol.iterator]: function*() {
               yield 11;
               yield 22;
               yield 33;
            }
         };
         for (const a of x) {
            document.write(a + " < br > "); 
         }
      </script>
   </body>
</html>

If we execute the above program, it will displays the number on the webpage.

Example 2

Consider the another scenario, where we are going to use the next() method of the iteratot to retrive the values in the sequence.

<html>
   <body>
      <style>
         body {
            font-family: verdana;
            color: #DE3163;
         }
      </style>
      <script>
         const x = {
            [Symbol.iterator]: function*() {
               yield "Ram";
               yield "Rahul";
               yield "Miryala";
            }
         };
         const a = x[Symbol.iterator]();
         document.write(a.next().value + " < br > ");
         document.write(a.next().value + " < br > "); 
         document.write(a.next().value);
      </script>
   </body>
</html>

On executing the above script, it will displays a text on the webpage.

Example 3

In the following example, we are going to iterate over the characters of a string.

<html>
   <style>
      body {
         font-family: verdana;
         color: #DE3163;
      }
   </style>
   <body>
      <script>
         const x = "WELCOME";
         const a = x[Symbol.iterator]();
         let result = a.next();
         while (!result.done) {
            document.write(result.value + " < br > ");
            result = a.next();
         }
      </script>
   </body>
</html>

When we execute the script, it will displays a characters of the string on the webpage.

Advertisements