Xen_mar
Xen_mar

Reputation: 9722

Call forEach on a string in JavaScript

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?

Upvotes: 8

Views: 19368

Answers (2)

Declan McKelvey-Hembree
Declan McKelvey-Hembree

Reputation: 1180

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.

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44125

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));

Upvotes: 18

Related Questions