Updated April 17, 2023
Introduction to JavaScript Iterator
In a programming language, an iterator is an object that enables us to traverse a list of objects. By using JavaScript iterator, we can allow our JavaScript objects to define their custom iteration behavior. It also provides us with some built-in type to iterator object but with default iteration behavior, i.e. Array, Map. To define customize iteration, one must have to implement the iterable protocol and need to implement the @@iterator method. Also, we need to follow the new standard, i.e. Symbol.iterator, here the symbol offers the name which is unique and should not conflict with other property names.
Symbol.iterator will return an object of iterator this iterator turn contains the following things below. Iterator protocol defines a way to generate the sequence of value and returns them when all values have been generated. If we want to iterate, the object must have to implement the next() method with the syntax and semantics below.
Method Available in JavaScript Iterator
Given below is the method available in JavaScript Iterator:
Property Value
next() Method: It is a no-argument method which returns at least the following two properties mentioned below:
- Value: It can return any JavaScript value. If the done value is true then this would be omitted. This can be of any type. It will contain the current value.
- done(Boolean): It will contain a Boolean value. It basically denotes all the values have been fetched or not. It will have a false value if the iterator is not able to produce the next value, or we can say not able to reach the end. In other words, do not need to specify the value for the done variable.
- It will have true value if the iterator has reach to the end of the sequence and able to produce the value.
So, the next() method always has to return an object with its properties done and value.
If we try to return a non-object value, e.g. false or undefined exception will be thrown. (Type Error :: iterator. Next() returned non-object value).
Examples of Built-in Iterator
Given below are the some of the examples showing iterator use:
Example #1
Code:
<!DOCTYPE html>
<html>
<body>
<h2>iterator in javascript</h2>
<script>
var str = 'IT';
typeof str[Symbol.iterator];
var iterator = str[Symbol.iterator]();
iterator.next(); // { value: "I", done: false }
iterator.next(); // { value: "T", done: false }
iterator.next();
console.log(iterator.next()); // { value: "I", done: false }
console.log(iterator.next()); // { value: "T", done: false }
console.log(iterator.next()); // { value: undefined, done: true }
</script>
</body>
</html>
Output:
Here from the above example, it is clear that if there is no sequence, it will return true, and the value would be undefined. Here we are using next() just to iterate over the object. Like we do in normal java programming when we use Java Iterator.
Example #2
We can also have another example in which we are going to use @@iterator.
Code:
<!DOCTYPE html>
<html>
<body>
<h2>iterator in javascript</h2>
<script>
var str = new String('IT'); // here we are creating explicate string object just to avoid auto-boxing.
str[Symbol.iterator] = function() {
return {
next: function() {
if (this._first) {
this._first = false;
return { value: 'bye', done: false };
} else {
return { done: true };
}
},
_first: true
};
};
console.log(str)
</script>
</body>
</html>
Output:
Example #3
We can have one more example to iterate over n natural numbers.
Code:
<!DOCTYPE html>
<html>
<body>
<h2>iterator in javascript</h2>
<script>
function num(till = 10) {
let k = 0;
const iteratorFx = () => {
console.log("iretaror called")
const iterator = {
next() {
k += 1;
if (k <= till) {
console.log("false" + k);
return { done: false, value: k };
}
console.log("true" + k);
return { done: true };
},
};
return iterator;
};
return {
[Symbol.iterator]: iteratorFx,
};
}
console.log("iterator called");
const numberList = num(10);
for (i = 0; i < numberList.length; i++) {
console.log(numberList[i] );
}
</script>
</body>
</html>
Output:
See the output in the developer’s console.
Here iterator syntax is more complex then ES6 provides us generator to create iterator object in more simpler way.
The generator also works the same as the iterator, but the syntax is different. It is a function that returns an iterator. But it takes an asterisk(*) symbol between the function keyword and the function name. this is the syntax for using a generator which provides more clarity on using iterator. In addition it uses the yield keyword.
Syntax of generator:
function * nameOfFunction(){};
Here is one advantage of yield function it pauses the function execution then returns the iterator object again resume the function execution whenever next() method is called.
It also contains two property value and done. This keyword return the iterator object with the mentioned property.
- Property : Value: Property is the result of the expression.
- Property : done: Property is used to specify that function has completed yet or not.
We can have a simple example to see the syntax and overall implementation of a generator.
a. User-Defined Iterable ::
Code:
<!DOCTYPE html>
<html>
<body>
<h2>iterator in javascript</h2>
<script>
var myFirstIterator = {};
myFirstIterator[Symbol.iterator] = function*(){
console.log("called");
yield 10;
yield 9;
yield 8;
};
[...myFirstIterator]; // [10, 9, 8]
console.log("fields added ");
console.log(myFirstIterator);
</script>
</body>
</html>
Output:
String, Array, Typed Array, Map and Set are all built-in iterables because each of their prototype objects implements an @@iterator method.
b. Build-In Iterator::
We have some build-in iterator available e.g. Map, Set, String, Array, Typed Array; these all are already available, because their prototype objects implement the @@iterator method.
Advantages of Iterator in JavaScript
Given below are the advantages of iterator in JavaScript:
- It provides a built-in method to traverse object.
- An exception is also handled properly.
- We can define custom iterator using [Symbol.iterator].
- Provide better performance.
Limitations of Iterator in JavaScript
Given below are the limitations:
- We cannot iterate collection object in backward direction by using iterator.
- We cannot pause the execution of iterator and return an object of iterator then again resume this can only be achieved by generator yield keyword.
Conclusion
By this article we conclude that Iterator is used to iterate over the collection in JavaScript. Basically it implements the Iterator protocol and having a method next () which return the objects from collection with two property mainly: value and done. We also so many build-in iterators like an array, map, set and type array, but they will follow the default iteration behavior. To overcome some syntax difficulty of iterator generator come into the picture. It also provides us yield keyword with pause and resume functionality over an iterator, but both have different syntax.
Recommended Articles
This is a guide to JavaScript Iterator. Here we discuss the introduction, method, examples, advantages and limitations, respectively. You may also have a look at the following articles to learn more –