Introduction
JavaScript offers several approaches to converting a number to String:
Number.prototypestoString()methodString()coercion- Template Literals way
Let’s explore each approach
Number.prototypestoString()method To convert a number to a string, wrap the number inside()brackets then call.toString()on it:
console.log((10).toString()) // prints '10'
// this does not work
console.log(1.toString()) // fails
String()coercion
We may directly convert a Number type to a String type by parsing the number to String(number)
const num = String(10)
console.log(num) // prints '10'
- Template literals
Template literals evaluate any expression inside ${expression} to a String
const mynum = `${10}`
console.log(typeof mynum) // string
Summary
String(num) and toString() method off Number.prototype. offer a cleaner way of converting a number to string in cases where to need to convert a number to string.
Found this article helpful? You may follow me on Twitter where I tweet about interesting topics on software development.