What’s the best way to JavaScript convert number to string? I’m looking for the most efficient method in terms of speed, clarity, and memory usage.
Here are some examples I’m considering:
String(n)
n.toString()
"" + n
n + ""
Which method is recommended?
This method is straightforward and clear, explicitly showing that you’re converting a number to a string. It’s efficient and widely used, making it a great choice for readability and understanding.
let num = 123;
let str = String(num); // "123"
This method is also clear and effectively converts a number to a string. It’s a bit more object-oriented, as it calls a method on the number itself. It’s generally efficient and commonly used in practice.
let num = 123;
let str = num.toString(); // "123"
You can also use “” + n or n + “”
This method uses string concatenation to convert the number to a string. While it can be the fastest in certain cases, it may be less clear to those unfamiliar with the trick. It’s not recommended if code clarity is a priority.
let num = 123;
let str = "" + num; // "123"