Why no default value for replace()?

Why didn't you add default value empty string for replace()? Now it replaces with "undefined" if no second argument what is absolutely useless and not applicable.
I think most cases of replace() are removing text and this default value would be very handy.
Can you add it now?

String.prototype.replace appears to have first appeared in the 3rd edition of the specification back in 1999. So it might be a challenge to answer definitively "why" the 2nd argument is not optional.

Generally speaking there is usually a desire to avoid attempting to change APIs that have been around for so long as there is a chance that they could break existing websites.

I know. But replacing with "undefined" is absolutely useless. Also, now using without the second argument is invalid (but no error, if it gave an error, there was no problem to add this). So lets discuss adding empty string as default value. To post in Ideas?

This one's pretty simple to test for with use counters. It may be possible to change.

And my suspicion is 0% of callers passing undefined or null for the replacement parameter actually intended to replace with the string "undefined" or "null".

1 Like

Many other string-taking functions do not default to the empty string. "".startsWith() also searches for the string "undefined", as is "".includes(). I don't think this is a special case.

"".startsWith() defaults to 0 index. "".includes() defaults to 0 index as well. They both have default value. They don't have to default to the empty string because they search but not replace. It is about the second argument, not about the first. Making default empty string for the first seems to be useless.

The argument doesn't default to anything - String.prototype.replace.length is 2, which means two arguments are required, always, and if you're surprised by the behavior when you omit one, that's on you.

2 Likes

It is about changing this (details in the first post) - the second argument, not the first.

It sounds like an argument to add the default empty string without concerns.

I would challenge that guess, this is not my experience. Also the method is named .replace(), not .remove(), so passing only one argument would look like something is missing.

For example, "".startsWith() can check not only from start, so exact correspondence to words is not adhered to.