What's the best way to convert a number to a string in JavaScript?

Learn what's the best way to convert a number to a string in javascript? with practical examples, diagrams, and best practices. Covers javascript, string, performance development techniques with vi...

The Definitive Guide to Converting Numbers to Strings in JavaScript

Hero image for What's the best way to convert a number to a string in JavaScript?

Explore various methods for converting numbers to strings in JavaScript, understand their performance implications, and learn best practices for different scenarios.

Converting a number to a string is a fundamental operation in JavaScript, frequently encountered when displaying numerical data to users, concatenating values, or interacting with APIs that expect string inputs. While seemingly straightforward, JavaScript offers several ways to achieve this, each with subtle differences in behavior, readability, and performance. This article will delve into the most common and effective methods, helping you choose the best approach for your specific needs.

Common Conversion Methods

JavaScript provides several built-in mechanisms for type coercion, including explicit and implicit conversions. Understanding these methods is key to writing robust and predictable code.

flowchart TD
    A[Number Input] --> B{Choose Method}
    B --> C["String() Constructor"]
    B --> D[".toString() Method"]
    B --> E["Template Literals"]
    B --> F["Concatenation (+ '')"]
    C --> G[String Output]
    D --> G
    E --> G
    F --> G

Overview of common number-to-string conversion methods

1. The String() Constructor

The String() constructor can be used as a function to convert a value to a string. When called without the new keyword, it performs type conversion. This is often considered a clear and explicit way to convert any data type to its string representation.

const num = 123;
const str = String(num);

console.log(str);      // "123"
console.log(typeof str); // "string"

const floatNum = 123.45;
const floatStr = String(floatNum);
console.log(floatStr); // "123.45"

const negativeNum = -50;
const negativeStr = String(negativeNum);
console.log(negativeStr); // "-50"

const zero = 0;
const zeroStr = String(zero);
console.log(zeroStr); // "0"

const bigInt = 12345678901234567890n;
const bigIntStr = String(bigInt);
console.log(bigIntStr); // "12345678901234567890"

const nan = NaN;
const nanStr = String(nan);
console.log(nanStr); // "NaN"

const infinity = Infinity;
const infinityStr = String(infinity);
console.log(infinityStr); // "Infinity"

Using the String() constructor for various number types

2. The .toString() Method

Every number in JavaScript has a .toString() method available via its prototype. This method is widely used and offers additional functionality for converting numbers to different bases (radix).

const num = 42;
const str = num.toString();

console.log(str);      // "42"
console.log(typeof str); // "string"

// Converting to different bases (radix)
const decimal = 255;
console.log(decimal.toString(16)); // "ff" (hexadecimal)
console.log(decimal.toString(2));  // "11111111" (binary)
console.log(decimal.toString(8));  // "377" (octal)

// Edge case: directly calling on a number literal requires parentheses
console.log((100).toString()); // "100"
// console.log(100.toString()); // SyntaxError: Invalid or unexpected token

Examples of .toString() with and without radix

3. Template Literals (Template Strings)

Introduced in ES6, template literals provide a clean and readable way to embed expressions within string literals. This method implicitly converts numbers to strings.

const num = 789;
const str = `${num}`;

console.log(str);      // "789"
console.log(typeof str); // "string"

const price = 99.99;
const message = `The price is $${price}.`;
console.log(message); // "The price is $99.99."

Using template literals for number-to-string conversion

4. String Concatenation with an Empty String

This is an older, but still common, technique that leverages JavaScript's implicit type coercion. When a number is added to a string (even an empty one), the number is coerced into a string.

const num = 456;
const str = num + '';

console.log(str);      // "456"
console.log(typeof str); // "string"

const anotherNum = 100;
const result = '' + anotherNum;
console.log(result); // "100"

Implicit conversion using string concatenation

Performance Considerations

For most applications, the performance difference between these methods is negligible. Modern JavaScript engines are highly optimized. However, in extremely performance-critical loops or large-scale data processing, minor differences might emerge. Generally, String() and concatenation (+ '') tend to be slightly faster than .toString() in some benchmarks, but these differences are often micro-optimizations that don't impact overall application performance significantly.

Hero image for What's the best way to convert a number to a string in JavaScript?

Conceptual performance comparison (actual results vary by engine and context)

Best Practices and Recommendations

Choosing the 'best' method often comes down to readability, explicitness, and specific use cases rather than raw performance.

1. Use String(value) for general explicit conversion

This is the most robust method for converting any value to a string, including null and undefined, without throwing errors.

2. Use number.toString() for number-specific conversions

Ideal when you are certain the value is a number and you might need to convert it to a specific base (e.g., hexadecimal, binary).

3. Use Template Literals (${value}) for embedding in strings

This method shines when you need to combine numbers with other strings, offering excellent readability and conciseness.

4. Avoid + '' for clarity in new code

While functional, + '' can be less explicit about the intention of type conversion. Prefer String() or template literals for better code readability.