Michael Phelps
Michael Phelps

Reputation: 3591

Typecasting.Difference between String() and + ''

Whats dif. between 2 methods :

null+'';
"null"
undefined + ''
"undefined"
NaN + ''
"NaN"
String(undefined)
"undefined"
String(null)
"null"

May have features to keep in mind ? maybe they are completely identical and performance ?

Upvotes: 0

Views: 75

Answers (2)

Cole Kettler
Cole Kettler

Reputation: 491

They will all return the same value, a string representation of a false-y value.

However, performance can vary radically.

http://jsperf.com/converting-null-undefined-nan-to-string

For instance, recent versions of Chrome and Firefox (35.0 and 28.0 at time of test, respectively) handle NaN + '' far more efficiently than String(NaN), whereas String() is more efficient for undefined and null. Safari 7.0 couldn't care less.

In more common cases (e.g. converting a Number to a String), concatenating an empty string vs. creating a new object vs. .toString() has been a subject of contention for a while. The results are interesting.

http://jsperf.com/string-vs-tostring-vs-empty-string-value/2

Mileage may vary heavily between browser versions. Also, blah blah premature optimization blah, do whatever is most clear in all but the most performance-sensitive environments. And be wary of unexpected type coercion, especially when checking false-y values.

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239453

In all the examples, the second way is using String literals to create strings. In the following cases,

null + ''
undefined + ''
NaN + ''

Since we concatenate with a string, the previous objects are also converted to their corresponding String representation. In the following expressions,

String(undefined)
String(null)

String constructor is used to construct the String representation of the objects. Internally, both String(undefined) and undefined + '' will be using the same function to convert to String representation.

I would say, using a single string literal may have a slight performance advantage over the other methods, because other methods will determine the string values at runtime but the JavaScript implementations can understand the String literals during compile time itself.

Upvotes: 1

Related Questions