Open In App

TypeScript Array Symbol.iterator Method

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
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.

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);
}

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();
}

Output:

Pankaj
Ram
Shravan
Jeetu

Next Article

Similar Reads