
If the result is primitive, return that result. ToPrimitive(Number): To convert an object obj to a primitive, invoke obj.valueOf().However, + uses the internal ToPrimitive(Number) operation (except for dates ), while String() uses ToPrimitive(String). The following table explains how ToString() operates on primitives.īoth approaches first convert an object to a primitive, before converting that primitive to string. “Internal” means: a function specified by the ECMAScript 5.1 (§9.8) that isn’t accessible to the language itself. But how do they actually do that? It turns out that they do it in slightly different ways, but usually arrive at the same result.īoth approaches use the internal ToString() operation to convert primitives to string. Until now you have heard that + and String() convert their “argument” to string. The latter is hardly ever useful in JavaScript, which is why you can usually forget about String as a constructor and concentrate on its role as converting to string.Ī minor difference between ""+value and String(value) The constructor produces an instance of the type String (an object). The function produces, as promised, a string (a primitive ). However, function and constructor produce completely different results: The only problem is that this function call will confuse some people, especially those coming from Java, because String is also a constructor. String(value): This approach is nicely explicit: Apply the function String() to value.


But that is a matter of taste, some people prefer this approach to String(value). As a way for converting a value to string, I find it less descriptive of one’s intentions. ""+value: The plus operator is fine for converting a value when it is surrounded by non-empty strings.That leaves us with approaches #2 and #3, which are basically equivalent. The problem with approach #1 is that it doesn’t work if the value is null or undefined. The three approaches for converting to string are: Three approaches for converting to string This blog post explains each way, along with its advantages and disadvantages.

In JavaScript, there are three main ways in which any value can be converted to a string.
