You want to convert a Number into a String, lucky you ! Javascript offers you differents ways to do that :
Number.prototype.toString()
String()
methodsEvery Number
in Javascript has a set of methods applied that you can directly call.
toString()
is one of them that you can directly call to convert your Number into String :
const myNumber = 60 const myNumberIntoString = myNumber.toString() console.log(myNumberIntoString) // "60" console.log(typeof myNumberIntoString) // "string"
String()
is a Javascript methods that you can directly call anywhere, and you need to pass the number you want to convert in parameter :
const myNumber = 60 const myNumberIntoString = String(myNumber) console.log(myNumberIntoString) // "60" console.log(typeof myNumberIntoString) // "string"
Template Strings is an ES6 feature that let you build string that are more readable when coding. You can use it to convert your Number into String :
const myNumber = 60 const myNumberIntoString = `${myNumber}` console.log(myNumberIntoString) // "60" console.log(typeof myNumberIntoString) // "string"
Last methods but not a very “good” one, it’s more for the example of how Javascript work more than something you should use. By adding an empty string directly to your number, Javascript will convert all the value into a String :
const myNumber = 60 const myNumberIntoString = '' + myNumber console.log(myNumberIntoString) // "60" console.log(typeof myNumberIntoString) // "string"
For better code readability I suggest that you use Javascript built-in methods Number.prototype.toString() or String(). Link to Mozilla foundation are provided for more information on them.