A JavaScript iterator is a construct that allows for traversing through a list or collection by utilizing an object or a specific pattern. Iterators are utilized through the method, which yields an object encapsulating the value. This implementation adheres to the iterator protocol, which outlines and produces the sequences. The subsequent value in the iterator sequence is found within the value property, while the done property indicates a boolean state that can either be true or false. This boolean value reflects whether the last value in the sequence has been consumed.
We can ascertain if the entity is iterable automatically by examining its prototype. This examination will reveal whether it possesses the method Symbol(Symbol.iterator).
The Symbol(Symbol.iterator): values function is found within Array.prototype. By default, arrays are iterable. Furthermore, String, Map, and Set are intrinsic iterables since each of their prototype objects includes a Symbol.iterator method.
Issues with the for loop
The variable serves as a mechanism within the for loop to monitor the index of the ranks array. Each iteration of the loop increments the value of the iterable variable, ensuring that it stays below the total count of elements present in the rankings array.
When a loop is contained within another loop, the complexity of the system escalates when utilizing a JavaScript loop. Furthermore, it becomes challenging to prevent errors while handling multiple variables within these loops.
Examples
In order to simplify the traditional looping mechanism and minimize the likelihood of errors associated with tracking loop indices, ECMAScript 6 introduced a new looping structure known as the "for...of" loop.
Example 1: The subsequent illustration demonstrates a JavaScript iterable using an array of numbers.
<!DOCTYPE html>
<html>
<body>
<h2> JavaScript Iterables to know for loop issues </h2>
</p>
<script>
// Create an Object of the array
let datas = ['Aaa', 'Bbb', 'Ccc', 'Dd', 'Ee'];
for (let a = 0; a < datas.length; a++) {
console.log(datas[a]);
}
</script>
</body>
</html>
Output
The iterable function displays the values within the loop.
Example 2
The subsequent example illustrates the use of a for loop in conjunction with a variable. In this case, we can utilize the loop repeatedly to process the information.
<!DOCTYPE html>
<html>
<body>
<h2> JavaScript Iterables to know for loop issues </h2>
<p id="demo_val"></p>
<script>
// Create a String to work as an array
const name_val = "Example";
// List all Elements of the string
let text_val = ""
for (const x of name_val) {
text_val += x + "<br>";
}
document.getElementById("demo_val").innerHTML = text_val;
</script>
</body>
</html>
Output
The iterable function displays the values during the iteration process.
Procedures for iteration
JavaScript offers an iteration protocol applicable to various data structures. The for...of loop, which is utilized within this protocol, defines the manner in which the data elements are traversed until completion.
The concept of the protocol can be dissected into the following components:
- Iterable in JavaScript
- Iterator in JavaScript
In accordance with the iterable protocol, an object designated as iterable is required to possess the Symbol.iterator property.
Iterables in JavaScript
Iterables refer to data structures that implement the Symbol.iterator method. Examples of such structures include arrays, strings, sets, and more.
An object qualifies as an iterator when it adheres to an interface (or API) that offers two specific functionalities:
- Are there any remaining elements?
- If there are, what is the current element?
An iterator can be technically defined as an object that includes a next method, which returns an object possessing the following two characteristics:
- Done: a boolean indicating whether there are more elements left to iterate through. The element currently being processed serves as the value of the iterable object.
- The Symbol.iterator method returns an object known as an iterator.
- The next method of the iterator protocol enables one-at-a-time access to each element of the iterable (data structure).
Iterators in JavaScript
Examples
The subsequent examples illustrate the fundamental iteration over both the numerical and character data present within the array.
Example 1: The subsequent example demonstrates a JavaScript iterable using an array of numbers.
<!DOCTYPE html>
<html>
<body>
<h2> JavaScript Iterables </h2>
<p> We can determine whether the entity is automatically iterable using Symbol(Symbol.iterator).
</p>
<p id = "demo_value">
</p>
<script>
// Create an Object of the array
my_value = {};
// Make it Iterable
my_value[Symbol.iterator] = function() {
let n = 0;
done = false;
return {
next() {
n1 += 15;
if (n1 == 150) {done = true}
return {value:n1, done:done};
}
};
}
let text_value = ""
for (const num_value of my_value) {
text_value += num_value +"<br>"
}
document.getElementById("demo_value").innerHTML = text_value;
</script>
</body>
</html>
Output
The iterable function displays the values within the loop.
Example 2: The subsequent example demonstrates a JavaScript iterable that utilizes the next method to iterate over the elements of an array by their numerical indices.
<!DOCTYPE html>
<html>
<body>
<h2> JavaScript Iterables </h2>
<p> We can determine whether the entity is automatically iterable using the next method ().
</p>
<p id = "demo_value">
</p>
<script>
// Iterable method and value
function my_Numbers() {
let n1 = 0;
return {
next: function() {
n1 += 20;
return {value:n1, done:false};
}
};
}
// Create Iterable
const n1 = my_Numbers();
n1.next(); // 20
n1.next(); // 40
n1.next(); // 60
//output: 80
document.getElementById("demo_value").innerHTML = n1.next().value;
</script>
</body>
</html>
Output
The iterable function shows the data in the loop.
Example 3: The subsequent illustration demonstrates the use of JavaScript iterables with an array of numbers by utilizing the Symbol(Symbol.iterator) method.
<!DOCTYPE html>
<html>
<body>
<h2> JavaScript Iterables </h2>
<p> We can determine whether the entity is automatically iterable using Symbol(Symbol.iterator).
</p>
<p id = "demo_value">
</p>
<script>
// Create an Object of the array
my_value = {};
// Make it Iterable of the array
my_value [Symbol.ite rator] = function() {
let n1 = 0;
done = false;
return {
next() {
n1 += 30;
if (n1 == 200) {done = true}
return {value:n1, done:done};
}
};
}
let text_value = ""
for (const num_value of my_value) {
text_value += num_value +"<br>"
}
console.log(text_value);
</script>
</body>
</html>
Output
The iterable function shows the data in the loop.
The function of the iterable argument
There is no necessity for you to implement iterators for the Array, Set, and Map data structures, as ES6 provides these functionalities natively.
The application creates an array object that produces a series of numbers within the range of (start, finish), ensuring that there is a specified interval between each number in the sequence.
Examples
The examples illustrate the process regarding the operations of the iterable argument.
Illustration 1: This illustration demonstrates a specific data array utilized with the iterable function. The first element represents the starting value, the final element indicates the concluding value, and the intermediate element denotes the incremental value used for iteration within the array.
<!DOCTYPE html>
<html>
<body>
<h2> JavaScript Iterables </h2>
<p> We can determine whether the entity is automatically iterable using Symbol(Symbol.iterator).
</p>
<p id = "demo_value">
</p>
<script>
// Create an Object of the array
class Seq_fun {
constructor( start = 0, end = Infinity, interval = 1 ) {
this.start = start;
this.end = end;
this.interval = interval;
}
[Symbol.iterator]() {
let counter = 0;
let nextIndex = this.start;
return {
next: () => {
if ( nextIndex <= this.end ) {
let result = { value: nextIndex, done: false }
nextIndex += this.interval;
counter++;
return result;
}
return { value: counter, done: true };
}
}
}
};
let evenNumbers = new Seq_fun(1, 20, 4);
for (const num of evenNumbers) {
console.log(num);
document.getElementById("demo_value").innerHTML = "please See the Console tab";
}
</script>
</body>
</html>
Output
The iterable function shows the data in the loop.
Example 2: This illustration demonstrates a specific array of data utilizing the iterable function. The first element represents the starting value, the final element denotes the concluding value, and the third element indicates the incremental value for iteration within the array. The methods next and symbol.iterable are employed for handling the numerical data.
<!DOCTYPE html>
<html>
<body>
<h2> JavaScript Iterables </h2>
<p> We can determine whether the entity is automatically iterable using Symbol(Symbol.iterator).
</p>
<p id = "demo_value">
</p>
<script>
// Create an Object of the array
class Seq_fun {
constructor( start = 0, end = Infinity, interval = 1 ) {
this.start = start;
this.end = end;
this.interval = interval;
}
[Symbol.iterator]() {
let counter = 0;
let nextIndex = this.start;
return {
next: () => {
if ( nextIndex <= this.end ) {
let result = { value: nextIndex, done: false }
nextIndex += this.interval;
counter++;
return result;
}
return { value: counter, done: true };
}
}
}
};
let evenNumbers = new Seq_fun(5, 100, 25);
let iterator = evenNumbers[Symbol.iterator]();
let result = iterator.next();
while( !result.done ) {
console.log(result.value);
result = iterator.next();
}
</script>
</body>
</html>
Output
The iterable function shows the data in the loop.
Cleaning up iterable
The [Symbol.iterator] can optionally provide the return function alongside the next method.
The return function is executed right away when the loop is concluded prematurely. This is the appropriate place to implement the code responsible for releasing all resources.
Illustration: this illustration demonstrates a specific collection of data utilizing the iterable function. We have the ability to streamline the for loop subsequent to processing the value.
<!DOCTYPE html>
<html>
<body>
<h2> JavaScript Iterables </h2>
<p> We can determine whether the entity is automatically iterable using Symbol(Symbol.iterator).
</p>
<p id = "demo_value">
</p>
<script>
// Create an Object of the array
class Seq_fun {
constructor( start = 0, end = Infinity, interval = 1 ) {
this.start = start;
this.end = end;
this.interval = interval;
}
[Symbol.iterator]() {
let counter = 0;
let nextIndex = this.start;
return {
next: () => {
if ( nextIndex <= this.end ) {
let result = { value: nextIndex, done: false }
nextIndex += this.interval;
counter++;
return result;
}
return { value: counter, done: true };
},
return: () => {
console.log('cleaning up...');
return { value: undefined, done: true };
}
}
}
}
let odd_Numbers = new Seq_fun(11, 20, 2);
for (const num of odd_Numbers) {
if( num > 7 ) {
break;
}
console.log(num);
}
</script>
</body>
</html>
Output
The iterable function displays the data while performing cleanup operations within the loop.
Conclusion
The JavaScript iterator illustrates the functionality, iterations, parameters, and various operational processes. It simplifies the intricacies associated with looping and its implementation.