How to convert a value to a string in JavaScript [translation]

Source: Internet
Author: User

Note: When I was reading ES5 two days ago, I came up with a question. Today I saw this article, but I just explained it clearly and translated it.
In JavaScript, there are three main ways to convert any value into a string. This article describes each method and its advantages and disadvantages.

1. Three Methods to convert strings
The three methods to convert values to strings are:

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

The problem with the first method is that it cannot convert null and undefined into strings. There are also the second and third methods, which have the same effect.

• "" + Value: any value can be converted to a String using an addition operator combined with an empty String. I think the code of this method is quite readable, but it is relative to a String (value, some people prefer this conversion method.
• String (value): This method is more readable and the only problem is that such function calls may confuse some people, especially those programmers familiar with Java, because String is also a constructor. note that it performs differently as a common function and as a constructor:

Copy codeThe Code is as follows:> String ("abc") === new String ("abc ")
False

> Typeof String ("abc ")
'String'
> String ("abc") instanceof String
False

> Typeof new String ("abc ")
'Object'
> New String ("abc") instanceof String
True

A String (an original value) is generated when it is used as a common function ). as a constructor, an instance of a String object is generated. the latter is rarely used in JavaScript, so you can basically ignore the use of String as the constructor, but remember that it is a conversion function.

2. "" + nuances between value and String (value)
Now you know that both + AND String () can convert their "Parameters" to strings. however, their conversion methods are still slightly different, but in almost all cases, the conversion results are the same.

2.1 convert the original value to a string
Both methods use the ToString () operation inside the engine to convert the original value to a string. the "internal operation" means that the operation function is in ECMAScript 5.1 (§ 9. (8), but the ES language itself cannot access it. the following table explains how ToString () converts the original value.

Parameters Result
Undefined "Undefined"
Null "Null"
Boolean Value "True" or"False"
Number Number as a string, such"1.765"
String Conversion not required

2.2 convert object values to strings

Both methods first convert the object value to the original value, and then convert the original value to a string. however, in this conversion, + uses the internal ToPrimitive (Number) operation (unless the date object is converted), while String () uses ToPrimitive (String ).

• ToPrimitive (Number): to convert an object value to the original value, first call obj. valueOf (). if the returned value is an original value, the original value is returned. if not, call obj. toString (). if the returned value is an original value, the original value is returned. otherwise, a TypeError exception is thrown.
• ToPrimitive (String): similar to the preceding method, only the obj. toString () method is called preferentially instead of obj. valueOf ().
By converting the following object, you can see the difference between them:Copy codeThe Code is as follows: var obj = {
ValueOf: function (){
Console. log ("valueOf ");
Return {}; // not the original value. Continue to execute
},
ToString: function (){
Console. log ("toString ");
Return {}; // not the original value. Continue to execute
}
};

// Run:
> "" + Obj
ValueOf
ToString
TypeError: Cannot convert object to primitive value

> String (obj)
ToString
ValueOf
TypeError: Cannot convert object to primitive value

2.3 results are usually the same
The difference mentioned above is almost impossible in practice, because most objects use the default inherited valueOf () method, and the return value is always the object itself.

Copy codeThe Code is as follows:> var x = {}
> X. valueOf () = x
True

Therefore, ToPrimitive (Number) usually skips the valueOf method to return the return value of toString () method, which is exactly the same as ToPrimitive (String. however, if this object is a Boolean, Number, or String object instance, its valueOf () will return an original value (the original value before being packaged by this object ). the two operations are performed as follows:

• ToPrimitive (Number) returns the return value of the valueOf () method of the object (the original value before being packaged) and the result after the ToString () operation.
• ToPrimitive (String) returns the return value of the toString () method of the object (the return value of the ToString () operation on the original value before the object is packaged ).
In this way, they still return the same results, but the conversion paths are different.

3. Conclusion

Which method should you choose to convert other types of values to strings? If you can ensure that the value is never null or undefined, you can use value. toString () to convert. otherwise, either "" + value or String (value) can be selected. Depending on your preferences, I think String (value) is more specific.

4. Related Articles

  1. JavaScript values: not everything is an object [difference between the original value and the object value]
  2. What is {} + {} in JavaScript? [Explains the working principle of the + operator]
  3. String concatenation in JavaScript [How to better connect multiple strings]
Related Article

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.