Converting An Object to String in JavaScript

There are three ways to convert an object to string in Javascript will be as below:

1. value.toString()
2. value+""
3. String(value) 

Limitation to Use

value.toString() can only be use when the value is not null or undefine.

value+”” can only be use when the value is non empty string.

String(value) this way looks like a function call which can be confusing especially to those who are coming from Java. For this case, String will be a constructor instead of a function. Output of this will be different from a  function.

For value.toString(), .toString() will convert primitive to string as below:

Argument Result
undefined "undefined"
null "null"
boolean value either "true" or "false"
number value the number as a string, e.g. "1.765"
string value no conversion necessary


Which approaches do you prefer to use?

If you know that value is not null or undefine, you can use  value.toString(). Otherwise,  ""+value and String(value) are mostly equivalent.

For more related information, please click here.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.