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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With