Ryan Rich
Ryan Rich

Reputation: 12075

Difference in converting objects to strings in JavaScript

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.

The first method

/\d+/g.toString()

The second method

/\d+/g + ''

Is there a difference between these two?

Upvotes: 1

Views: 62

Answers (3)

Esailija
Esailija

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

Denys Séguret
Denys Séguret

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

Arpit
Arpit

Reputation: 12797

Both are same. the second one will also call the toString().

Upvotes: 0

Related Questions