3 Ways to Convert Numbers to Strings in JavaScript
We have looked at a few ways to convert strings to numbers. Now, let's look at how to convert numbers to strings in Javascript.
Let's dive in!
1. String()
Object
The String()
object is the most straightforward and recommended way to convert a number to a string in JavaScript. When you pass a number to the String()
function, it creates a string representation of the number. This method is both safe and descriptive.
String(123.45) //'123.45'
2. Concatenating the Empty String
This might sound a little strange, but it's actually a really effective way to convert a number to a string. You simply concatenate the number with an empty string, and JavaScript will convert it to a string for you.
"" + 22 //"22"
3. toString()
Method
The toString()
method is a built-in JavaScript function that returns a string representation of an object. It can be used to convert a number to a string by calling it on the number.
let num1 = 5.14; let num2 = 21; num1.toString(); // "5.14" num2.toString() // "21"
Be aware that that the toString() method throws an error when called on undefined or null values.
let num3 = null num3.toString() // throws error
Get my free, weekly JavaScript tutorials
Want to improve your JavaScript fluency?
Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.
Join today, and level up your JavaScript every Sunday!
Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.