JavaScript is a dynamic and flexible, non strongly-typed language. While it opens a few doors for erroneous coding patterns, it also comes with several advantages. One of those is the flexibility of doing something in multiple ways.
Here in the code below, I’m demonstrating 6 different ways to convert a number into a string:
1. Convert using the String() constructor
const someNumber = 10
const someString = String(someNumber)
console.log(someString)
console.log(typeof someString)
//output
10
string
Code language: JavaScript (javascript)
2. Convert using toString() method
const anotherNumber = 20
const anotherString = anotherNumber.toString()
console.log(anotherString)
console.log(typeof anotherString)
//output
20
string
Code language: JavaScript (javascript)
3. Convert by pre-appending empty string
const yetAnotherNumber = 30
const yetAnotherString = '' + yetAnotherNumber
console.log(yetAnotherString)
console.log(typeof yetAnotherString)
//output
20
string
Code language: JavaScript (javascript)
4. Convert by post-appending empty string
const newNumber = 40
const newString = newNumber + ''
console.log(newString)
console.log(typeof newString)
//output
40
string
Code language: JavaScript (javascript)
5. Convert using string interpolation syntax
const moreNumber = 50
const moreString = `${moreNumber}`
console.log(moreString)
console.log(typeof moreString)
//output
50
string
Code language: JavaScript (javascript)
6. Convert using JSON.stringify()
const oneMoreNumber = 60
const oneMoreString = JSON.stringify(oneMoreNumber)
console.log(oneMoreString)
console.log(typeof oneMoreString)
//output
60
string
Code language: JavaScript (javascript)
If you know of more ways, sound off in the comments below!