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.
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].forEachvery easily, and you can also dofor (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);
});
- can damage the future syntax of the language if enough script-writers define such a thing (see what happened with
Array.prototype.containsandArray.prototype.flatten)
So, it’s doable, but it’s probably not a good idea.