What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?
Some examples:
String(n)
n.toString()
""+n
n+""
What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ?
Some examples:
String(n)
n.toString()
""+n
n+""
Explicit conversions are very clear to someone that's new to the language. Using type coercion, as others have suggested, leads to ambiguity if a developer is not aware of the coercion rules. Ultimately developer time is more costly than CPU time, so I'd optimize for the former at the cost of the latter. That being said, in this case the difference is likely negligible, but if not I'm sure there are some decent JavaScript compressors that will optimize this sort of thing.
So, for the above reasons I'd go with:
n.toString()
orString(n)
.String(n)
is probably a better choice because it won't fail ifn
is null or undefined.The only valid solution for almost all possible existing and future cases (input is number, null, undefined, Symbol, anything else) is
String(x)
. Do not use 3 ways for simple operation, basing on value type assumptions, like "here I convert definitely number to string and here definitely boolean to string".Explanation:
String(x)
handles nulls, undefined, Symbols, [anything] and calls.toString()
for objects.'' + x
calls.valueOf()
on x (casting to number), throws on Symbols, can provide implementation dependent results.x.toString()
throws on nulls and undefined.Note:
String(x)
will still fail on prototype-less objects likeObject.create(null)
.If you don't like strings like 'Hello, undefined' or want to support prototype-less objects, use the following type conversion function:
I think it depends on the situation but anyway you can use the
.toString()
method as it is very clear to understand.In my opinion
n.toString()
takes the prize for its clarity, and I don't think it carries any extra overhead.Other answers already covered other options, but I prefer this one:
Short, succinct, already used in many other places (if you're using a modern framework / ES version) so it's a safe bet any programmer will understand it.
Not that it (usually) matters much, but it also seems to be among the fastest compared to other methods.
You can call
Number
object and then calltoString()
.Number.call(null, n).toString()
You may use this trick for another javascript native objects.