JavaScript

String Iteration Methods in JavaScript

In JavaScript, a string iterator is a method that permits traversing the characters present in a string. By utilizing the JavaScript string iterator, we enable the string added in our code to define their custom iteration behavior. To create a string iterator, you can either use the built-in JavaScript “string @@iterator method” or go for the user-defined string iterator, which can be created with the help of the “Generators”.

This write-up will discuss string iteration methods in JavaScript. Moreover, the examples related to the string @@iterator method and JavaScript Generators will be also demonstrated. So, let’s start!

String @@iterator method in JavaScript

The string iteration method in JavaScript allows you to iterate over the added string in your program. You can make any string iterable by implementing the “@@iterator” method. The string “@@iterator” method returns an iterator object that iterates over all of the code pointed to the added string.

The “String[@@iterator]” method is a built-in JavaScript property of a string. By calling the “@@iterator” String property, you can create a string iterator, and in place of “@@iterator,” you have to utilize the “Symbol.iterator” as constant.

Syntax of string iterator method

var iterator = str[Symbol.iterator]();

Here, “iterator” is the name for our string iterator, and the string which needs to be iterated is represented as “str”.

Using string @@iterator method with next()

In your JavaScript code, you can get your string iterator object using the “next()” method. The “next()” method outputs the keys “Value” and “done,” which comprises a boolean value. The Value key contains the current key value. The done key indicates that if the value is fetched or not, with the “true” and “false” value, where “true” represents that the iteration process is finished and “false” denotes that there exist more values for the iteration.

Now, let’s check out some JavaScript examples related to the string @@iterator method.

Example 1: Using string @@ iterator method without loop

This example will show you how to use the string @@iterator method in your JavaScript program to iterate a specific string. For this purpose, first of all, we will string having ‘MN’ as its value:

var str = 'MN';

In the next step, we will create a string iterator for our “str” string:

var iterator = str[Symbol.iterator]();

If you do not want to use loops for the iteration, you have to invoke the “next()” method according to the length of your string. For instance, we will execute the “iterator.next()” method three times. For the first two times, the “done” value will return false, and when we invoke the specified method a third time, it will return “true” as the iteration is completed and no value is left to iterate:

console.log(iterator.next()); // { value: "M", done: false }
console.log(iterator.next()); // { value: "N", done: false }
console.log(iterator.next()); // { value: undefined, done: true }

Have a look at the provided code and its output:

Example 2: Using string @@ iterator method with for loop

You can also use “loops” to handle the repeated task of string iteration. Want to know how? If yes, then follow the below-given example.

Firstly, we will define a string “str” for which we want to create a string “iterator”:

const str = 'MNM';
const iterator = str[Symbol.iterator]();

Next, we will assign the value of the “iterator.next()” function to our “theChar” variable:

let theChar = iterator.next();

Then, we will add a simple “for loop,” which will perform the iterator according to the string length property “str.length”. For each iteration of the for loop, the key value and the done value will be displayed to the console window, and the “theChar” will then move to the next string iteration:

  for(let i = 0; i < str.length ;i++) {
  console.log(theChar.value , theChar.done);
  theChar = iterator.next();
}

Here is the complete look of the provided example along with its output:

Example 3: Using string @@ iterator method with for..of loop

Using the for..of loop, you can utilize the @@iterator method to iterate over the string data. For each for-of loop iteration, you have to call the “next() method.value” for the iteration purpose.

For instance, we have defined a simple string having “MNM” as its value in our JavaScript program:

const str = 'MNM';

In the next step, we will create a string iterator for our added “str” string:

const iterator = str[Symbol.iterator]();

After that, we will assign the iterator value to the “theChar” variable, which will iterate its value using the “next()” method in the for loop:

const iterator = str[Symbol.iterator]();

Lastly, you can add the “for..of” loop to iterate over the “str” string as follows:

//By utilizing the for-of loop
  console.log("Iterating with for-of loop :")
  for(let i of str)
  {
    console.log(i)
  }

The below-given image shows the output of our JavaScript program:

Generators in JavaScript

Generators are another helpful feature of JavaScript that permits you to define a function and then use it for creating the string iterator. This procedure is less prone to error and offers an efficient way to create string iterators.

Syntax of generators

To use the generator in your JavaScript program, you have to follow the below-given syntax:

function* () {
  yield " character1"
  yield " character2"
  ....
}

Here, “*” indicates that we are creating an anonymous function. The keyword “yield” is added to function the execution and returns the iterator object. After doing so, it will again resume its operation.

Example: Creating user-defined string iterator in JavaScript

In JavaScript, you can also create a user-defined string iterator by utilizing generators. To do so, firstly create a “myIterator” object:

var myIterator = {};

Now, define the generator function while specifying the point where the execution will pause with the “yield” keyword. Also, when the generator function is invoked, a “called” string will be shown in our console window:

myIterator[Symbol.iterator] = function*(){
console.log("called");
yield "M";
yield "N";
yield "O";
};
[...myIterator];

After this point, all of the field values will be added to the “myIterator” object:

console.log("fields added ");
console.log(myIterator);

Here is the output which we got from executing the above-given example:

Conclusion

Using the string @@iterator method and generators, you can easily perform the string iteration process in JavaScript. The string @@iterator method implements the iterator protocol, including the next() method, which returns the characters from collection having two properties value and done. Whereas, Generators let you create a user-defined string iteration method in which you can add the pausing point for the iteration according to your requirements. This write-up discussed string iteration methods in JavaScript. Moreover, the examples related to the string @@iterator method and Generators are also demonstrated.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.