Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I add forEach method to String prototype from Array prototype?

As we know there is a .forEach() method for arrays in JavaScript. But Strings don’t have that method built in.

So, is there any issue regarding the following code snippet:
String.prototype.forEach = Array.prototype.forEach ?

This setting helps me to use .forEach for Strings.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let myName = "Avetik";   

String.prototype.forEach = Array.prototype.forEach;

myName.forEach(char => {

console.log(char);
})

The above code works fine and outputs all chars of my name.

You already guessed that I am a newbie in JS.

>Solution :

You can, but:

  • it’s confusing (other developers working on the same codebase could well be very confused at seing such a method called on a string)
  • can lead to fragile code (if you define String.prototype.forEach, it may interfere with other code that uses methods on the String prototype)
  • doesn’t help much: you can do [...str].forEach very easily, and you can also do for (const char of str) { very easily
// Say we want to iterate over this string:
const str = 'str';

// without adding a method to the prototype. Easy:

// One method:
for (const char of str) {
  console.log(char);
}

// Another method:
[...str].forEach((char) => {
  console.log(char);
});

So, it’s doable, but it’s probably not a good idea.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading