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"