Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 299
Xen_mar Avatar asked Jun 09 '26 22:06

Xen_mar


1 Answers

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));
like image 148
Jack Bashford Avatar answered Jun 12 '26 11:06

Jack Bashford



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!