DEV Community

Cover image for How to Convert a Number into a String in JavaScript?
Caspian Grey
Caspian Grey

Posted on

How to Convert a Number into a String in JavaScript?

In JavaScript, numbers and strings are different data types.
Sometimes you need to convert a number into a string — for example, when displaying values in the UI, concatenating text, or sending data to an API.

JavaScript provides multiple ways to do this. In this blog, we’ll look at four popular and commonly used techniques:

  1. toString()
  2. String() function
  3. Concatenation with an empty string
  4. Template literals

1. Using toString()

The toString() method converts a number directly into a string.

Example:

let num = 100;
let str = num.toString();

console.log(str);        // "100"
console.log(typeof str); // string
Enter fullscreen mode Exit fullscreen mode

When to use?

  • When you are sure the value is a number
  • Clear and explicit conversion

Note: toString() cannot be used on null or undefined, otherwise it will throw an error.

2. Using the String() function

The String() function converts any value into a string.

Example:

let num = 250;
let str = String(num);

console.log(str);        // "250"
console.log(typeof str); // string
Enter fullscreen mode Exit fullscreen mode

When to use?

  • Safe and reliable
  • Works even with null and undefined

This is one of the safest and most recommended ways.

3. Using concatenation with an empty string ("")

When you add a number to an empty string, JavaScript automatically converts the number into a string.

Example:

let num = 75;
let str = num + "";

console.log(str);        // "75"
console.log(typeof str); // string
Enter fullscreen mode Exit fullscreen mode

When to use?

  • Quick and simple
  • Common in older codebases

This method is less readable, especially for beginners.

4. Using Template Literals

Template literals (introduced in ES6) convert values to strings automatically.
Example:

let num = 42;
let str = `${num}`;

console.log(str);        // "42"
console.log(typeof str); // string
Enter fullscreen mode Exit fullscreen mode

When to use?

  • Modern JavaScript
  • Very readable Great when combining numbers with text

Example with text:

let age = 21;
console.log(`My age is ${age}`);
Enter fullscreen mode Exit fullscreen mode

These are some common techniques used to convert a number into a string in JavaScript. I hope you learned something new and enjoyed the article. Like it if you enjoyed.

Top comments (0)