TypeScript Array Symbol.iterator Method
Last Updated :
06 Feb, 2024
In TypeScript the Symbol.iterator function plays a role, in allowing iteration over arrays using for…of loops and other iterator-based mechanisms. This built-in function eliminates the need, for definition when working with arrays simplifying the process of accessing elements in a manner.
Syntax:
const iterator: Iterator<T> = array[Symbol.iterator]();
Parameter:
- None: No parameter is required.
Return Value:
- It returns the iterable point that can be accessed in a for loop for getting values of that array.
Example 1: We will iterate each element of an array by using a, for…of loop and see the working of Symbol.iterator Method.
Javascript
let numbers: number[] = [1, 2, 3, 4, 5,
6, 7, 8, 9, 10];
let iterator = numbers[Symbol.iterator]();
for (let num of iterator) {
console.log(num);
}
|
Output:
1
2
3
4
5
6
7
8
9
10
Example 2: We are going to manually iterate using the next method and see the working of Symbol.iterator Method.
Javascript
let geeks: string[] = [ 'Pankaj' , 'Ram' , 'Shravan' , 'Jeetu' ];
let iterator = geeks[Symbol.iterator]();
let output = iterator.next();
while (!output.done) {
console.log(output.value);
output = iterator.next();
}
|
Output:
Pankaj
Ram
Shravan
Jeetu
Share your thoughts in the comments
Please Login to comment...