JavaScript Iterator
Posted by Superadmin on May 02 2023 14:02:50

JavaScript Iterator

JavaScript Iterator

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:

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:

JavaScript Iterator 1

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:

JavaScript Iterator 2

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:

over n natural numbers

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.

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:

are all built-in

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:

Limitations of Iterator in JavaScript

Given below are the limitations:

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.