8

I am not that experienced in JS so maybe this is a very naive question. I tried to call

"".forEach((e, i) => {
    console.log(e)
})

And I get an error saying that forEach is not a function for a string. Yet when I call:

Object.getOwnProperyNames("")

I can clearly see that forEach() is in the prototype of the string and of type function.

Why can I not call it on a string?

5
  • 5
    You can't use it on a string because it's not available on the String prototype.
    – Pointy
    Commented Aug 25, 2019 at 8:28
  • 2
    I can clearly see that forEach() is in the prototype of the string and of type function. where you can see this, forEach is not available on String Commented Aug 25, 2019 at 8:30
  • 6
    The array returned from .getOwnPropertyNames() has a .forEach method because it's an array.
    – Pointy
    Commented Aug 25, 2019 at 8:31
  • What do you expect to be logged in that inner function? Why should a string have a forEach function?
    – Nico Haase
    Commented Aug 25, 2019 at 8:33
  • Sidebar: Isn't Object.getOwnProperyNames("") not the correct way to do this anyway? Shouldn't it be cObject.getOwnPropertyNames(String.prototype)? Commented Aug 25, 2019 at 8:42

2 Answers 2

18

Object.getOwnPropertyNames returns an array, and you can iterate through an array - no surprises there.

As for iterating through a string with a forEach loop, you can't - you can only use a for loop. That is, iterating through a string. A quick and easy way to use forEach is to spread the string into an array:

[..."Hello, World!"].forEach((e, i) => console.log(e));

Or, if it contains certain characters:

Array.from("Hello, World!").forEach((e, i) => console.log(e));
2
  • This works as described in the browser console but I can't get it to compile in my IDE.
    – Alex
    Commented Jun 14, 2021 at 0:58
  • This is no criticism of the answer, but using the spread operator or Array.from would convert the string to an array via the charAt method, no? Or require a method of iteration for each character in some way. If that's the case, I question the value of performing a duplicate operation that could be done with a single loop.
    – GHOST-34
    Commented Oct 14, 2021 at 19:30
0

Object.getOwnPropertyNames("") only returns ["length"]. The .foreach you're seeing, I assume in Inspector, is a property of the array returned (ie. you could call ["length"].foreach(...)). It does not imply that string has a foreach method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.