HomeContact
Javascript
How to convert a Number into a String using Javascript
September 17, 2020
1 min

Table Of Contents

01
.toString() methods provided to number
02
String() methods
03
Template Strings
04
Concatenating an empty string

You want to convert a Number into a String, lucky you ! Javascript offers you differents ways to do that :

  • Number.prototype.toString()
  • String() methods
  • Directly save a number in a template String
  • Concatenating an empty string

.toString() methods provided to number

Every 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() methods

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

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"

Concatenating an empty 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.


Tags

javascript

Related Posts

How to remove space from String using Javascript
February 04, 2021
1 min
© 2023, All Rights Reserved.

Quick Links

Contact Us

Social Media