Open In App

TypeScript Array Symbol.iterator Method

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// TypeScript code with annotations
let numbers: number[] = [1, 2, 3, 4, 5,
    6, 7, 8, 9, 10];
 
// Here we use Symbol.iterator to get the default iterator
let iterator = numbers[Symbol.iterator]();
 
for (let num of iterator) {
    console.log(num);
}
 
// author: Pankaj Kumar Bind


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




// TypeScript code with annotations
let geeks: string[] = ['Pankaj', 'Ram', 'Shravan', 'Jeetu'];
 
// Here we use Symbol.iterator to get the default iterator
let iterator = geeks[Symbol.iterator]();
 
// Manually iterating using the next method
let output = iterator.next();
 
while (!output.done) {
    console.log(output.value);
    output = iterator.next();
}
// author: Pankaj Kumar Bind


Output:

Pankaj
Ram
Shravan
Jeetu


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads