1

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?

4
  • @TimPietzcker Implicit conversions are an important part of the language's practice, so it's perfectly normal to do it. Commented May 16, 2013 at 13:01
  • @dystroy: Ah, so that's why [] + [] results in "", {} + [] results in 0 and {} + {} results in NaN. I think I'll stick with Python :) Commented May 16, 2013 at 13:03
  • @TimPietzcker I don't pretend you don't have to stick to some readability principles. In fact, more than in other languages, an important part of the work of the coder should be dedicated to making its code obvious and natural, but that's not so hard. Commented May 16, 2013 at 13:08
  • @TimPietzcker should be ({} + []) ("[object Object]") -- you would never write actual code to have that in statement context where it results in 0. Commented May 16, 2013 at 13:19

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+a rather is a stricter parseFloat
2

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') .

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.