Reputation: 12075
I'm wanting to convert an object to a string in JavaScript and I'm confused on which method I should use. I have a simple example below.
/\d+/g.toString()
/\d+/g + ''
Is there a difference between these two?
Upvotes: 1
Views: 62
Reputation: 140228
The second method additionally works with null/undefined
and is not that unclear:
a.toString() //Fails with null/undefined
a + "" //Works with anything
You might also find other idioms such as +a
useful, which is a much stricter parseFloat
.
Upvotes: 3
Reputation: 382274
No, there's no difference, when an object must be converted to a string, the toString
function is called.
More precisely, the toPrimitive
conversion with hint "string" is applied, and it's defined here in the ECMAScript specification for an object.
Note that when you pass null or undefined (see the spec), only the addition scheme would work. That, along the reduced verbosity, explain why toString
is rarely explicitly called in JavaScript. Implicit conversions are an important part of the language's practice, so it's perfectly normal to use this method, just as you often prefix a string with +
to convert it to a number (i.e. +'33'
) .
Upvotes: 2