The explanation is fairly straight forward - in apis where a string is expected, but a non-string is passed, JS will attempt to call .toString() on that method. Vanilla objects are the base case and return [object Object] when .toString() is called.
It would be a rather weird use case fo RegExp to need to recieve some object that intentionally implements toString in order to produce a valid regexp but that would be an inconsistency with standard expectations that .toString is the standard fallback.
This exists in other numeric apis too, where valueOf is attempted on objects.
View all comments
Show parent comment
1
u/_xiphiaz Mar 21 '24
The explanation is fairly straight forward - in apis where a string is expected, but a non-string is passed, JS will attempt to call
.toString()on that method. Vanilla objects are the base case and return[object Object]when.toString()is called.It would be a rather weird use case fo RegExp to need to recieve some object that intentionally implements toString in order to produce a valid regexp but that would be an inconsistency with standard expectations that .toString is the standard fallback.
This exists in other numeric apis too, where
valueOfis attempted on objects.