JS to convert a variable to a string

Source: Internet
Author: User

Translator by: The details of the language to understand it, do not need to be too serious, but if you do not know, it is not very good.

    • Original: Converting a value to string in JavaScript
    • Translator: Fundebug

In order to ensure readability, this paper uses free translation rather than literal translation. In addition, the copyright of this article belongs to the original author, translation is only used for learning.

For JavaScript, there are 3 different ways to convert a variable to a string. This blog will describe these methods in detail and compare their pros and cons.

3 different methods

3 ways to convert a variable to a string are as follows:

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

When value is null or undefined , the 1th method is not. and Method 2 and Method 3 are basically the same.

    • ""+value: Adds value to an empty string to convert it to a string. This is a slightly obscure technique that may make it difficult for others to understand the intentions of developers. However, this is a matter of opinion, some people prefer this method.

    • String(value): This method is very clear: Use the string () function to convert value to a string. However, there are two different uses ofString () , which are confusing, especially for Java developers. When string () and operator new are used as constructors, it returns a newly created string object, and when string () is called without the new operator, the It only converts value to the original string. The two are very different:

>string ("fundebug") = = = new string ("Fundebug") false>typeof String ("Fundebug") ' String '>string ("Fundebug") instanceof string false>typeof New String ("Fundebug") ' object '>new string ("Fundebug") instanceof string true

In fact, it is not uncommon to use string () as a constructor, so it is only good to use it to convert strings.

Nuances of "" +value and string (value)

""+valueAnd String(value) Both can convert the value to a string, how do they do it? In fact, they have the same results, but the methods are slightly different.

Converting a primitive base type to a string

Both methods use the intrinsic function ToString () to convert the primitive base type to a string. The ToString () function is defined in ECMAScript 5.1 (§9.8) , but is not intended to be used directly, so it is called an intrinsic function. The following table shows how the ToString () function converts the primitive base type to a string:

Parameters Results
undefined "undefined"
null "null"
Boolean "true"Or"false"
Number Converts a number to a string, for example:"1.765"
String No conversion required
Convert an object to a string

Before being converted to a string, both methods first convert the Object to primitive. The difference is that the ""+value intrinsic function toprimitive(number) is used (except for the date type) and the String(value) intrinsic function toprimitive (String)is used.

    • Toprimitive (number): Call obj.valueofFirst and return if the result is primitive , otherwise call obj.tostring ()If the result is Primitive is returned, otherwise TypeErroris returned.
    • Toprimitive (String): Similar to toprimitive (number) , except that obj.tostring ()is called first, and then obj.valueof () is called. .

The following examples can be used to understand the difference, withobj as follows:

var obj = {valueOf: function () {console.log ("valueOf"); return {};},tostring: function () {console.log ("toString"); return {};}};

Call Result:

> " " + objvalueoftostringtypeerror:cannot Convert object to primitive value > String (obj) tostringvalueofTypeerror:cannot Convert object to primitive value
They have the same results.

""+valueString(value)it's different, but we can hardly feel it. Because most object uses the default valueOf (), it returns the object itself:

> var x = {}> x.valueof () = = = Xtrue

Because the valueOf () return value is not primitive, toprimitive (number ) skips valueOf ()and returns The return value of toString () . In this way, the return value is the same as toprimitive (String) .

When object is a Boolean, number, or String instance, valueOf () returns primitive. This means that the process of calculating the two is as follows:

    • Toprimitive (number): valueOf() returns the primitive value and then converts to a string using ToString () .
    • Toprimitive (String): toString() converts the primitive value to a string through the ToString () function.

Although the computational process is different, the results are the same.

Conclusion

So which method should you choose? If you can make sure that the value is not null and undefined, then you might want to use it value.toString() . Otherwise, you can only use ""+value and String(value) , they are basically the same.

Reference
    1. JavaScript Values:not Everything is an object
    2. What's {} + {} in JavaScript?
    3. String concatenation in JavaScript
    4. JavaScript String Object

Copyright NOTICE: Please specify the author fundebug and this address:https://blog.fundebug.com/2017/09/18/value-to-string/

JS to convert a variable to a string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.