String [@@iterator]( ) Method is used to make String iterable. [@@iterator]() returns iterator object which iterate over all code point of String. String[@@iterator] is Built – in Property of String.
We can use this method by making a string iterator. We can make an iterator by calling the @@iterator property of String. In place of @@iterator, we use Symbol.iterator constant.
// Test String var str ="String"; // iterator to String var iter = str[Symbol.iterator]();
We can get iterator object with next(). It returns the object with keys value and done. The value key holds a real iterating value string and the done key holds true or false if iteration finishes it keeps true if not then false. We can get the value of the object by str.value and done by str.done.
Example 1: Below is the code that illustrates the use of above approach.
"G" false "F" false "G" false
We can use @@iterator method without assigning iterator by using for — of loop to iterate over-collection of data by using @@iterator method. On each iteration for — of loop call _next().value to iterate in the collection.
Example 2: Below is the code that illustrates the use of above approach.
"G" "F" "G" Iterating by for-of loop : "G" "F" "G"