2

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.

Avetik Nersisyan
  • 327
  • 3
  • 13
  • How would forEach work on a string???? What do you expect to happen when you call it? Also note, extending the prototype is not seen as a best practice. – epascarello Nov 11 '21 at 22:40
  • *"So, is there any issue regarding the following code snippet"* So did you try it? What happened? – epascarello Nov 11 '21 at 22:41
  • Oddly enough this works https://codesandbox.io/s/quirky-pateu-d39n1?file=/src/index.js:0-127 – Abdullah Khan Nov 11 '21 at 22:43
  • Not oddly enough, many of the methods in array are intentionally generic to work with anything that has a length property and can be accessed with brackets. `shift is intentionally generic; this method can be called or applied to objects resembling arrays.` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift – Ruan Mendes Nov 12 '21 at 00:03

3 Answers3

3

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
2

You can add your own wrapper...

I can hardly resist such bad ideas!
My advice, do it, and wait for the day or such practices will turn against you dearly. Then you will have the measure of such an error, which I hope will definitely dissuade you from playing with language syntax, and with any luck you might be able to become a computer language guru.

if(typeof String.prototype.forEach !== "function") {
  String.prototype.forEach = Array.from(this).forEach
};

// sample usage :
let abc = 'abc'

abc.forEach((letter, index)=> console.log(letter,index))

but it would be better to use a less ambiguous name

if(typeof String.prototype.forEachLetter !== "function") {
  String.prototype.forEachLetter = Array.from(this).forEach
};

// sample usage :
let abc = 'abc'

abc.forEachLetter((letter, index)=> console.log(letter,index))
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
1

.forEach() is inherently a function for arrays (groups of multiple things). A string is just 1 thing, there's no way to do something for "each" when there's only 1.

You can use .split() on a string to turn it into an array of every character. Then do whatever array operations you want on the result of that. And then .join() on the array to turn it back into a string if you need to.

var myString = "beans";
var myArray = myString.split(); // this will be an array of 5 strings: ['b', 'e', 'a', 'n', 's']
GregT2207
  • 60
  • 1
  • 6
  • 2
    Not entirely true, at fundamental level,a string is just an array of chars. So from what i have checked it works. You can try it here https://codesandbox.io/s/quirky-pateu-d39n1?file=/src/index.js:0-127 – Abdullah Khan Nov 11 '21 at 22:46
  • @AvetikNersisyan … I fully agree with *Abdullah Khan* and therefore hereby want to encourage the discovering spirit of the OP. While going on an educational journey into the language core this kind of question shows own thinking / curios mind. Keep on with this attitude. And even though augmenting the prototype of built in objects in my opinion is not 100% evil, the OP's string enhancement is arguable and nothing one would necessarily apply to any kind of enterprise code. But the answer of the OP's question *"Can I add forEach method to String prototype from Array prototype?"* is… Yes one can. – Peter Seliger Nov 11 '21 at 23:34