AD JB Toolbox 01 EN

JavaScript String(): Convert Numbers to Strings

Use String(value) to convert a number to a JavaScript string. The returned value has the type string; adding two converted values with + joins their text instead of adding the numbers. String() also accepts values such as booleans, null and undefined.

String() syntax and return value

String(value)
String(123)       // "123"
String(0)         // "0"
typeof String(12) // "string"

Pass the value or variable you want to convert. The typeof operator identifies its type: the number 12 and the string "12" can look identical on a page but behave differently in calculations and comparisons. MDN explains the function and constructor forms of String().

Call Returned string Meaning
String(125) "125" Text representing a number
String(false) "false" A boolean becomes text
String(null) "null" Not an empty string
String(undefined) "undefined" A missing value is represented as text
String() "" Omitting the argument returns an empty string

Complete example: addition versus concatenation

Save the following code as string-example.html in UTF-8 and open it in a browser. It requires no library. The result is assigned to textContent, which displays text without interpreting it as HTML.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>String() and numeric addition</title>
  <style>
    body { margin: 24px; font: 16px/1.7 sans-serif; }
    input, button, select { font: inherit; max-width: 100%; }
    label { display: block; margin-top: 12px; }
    #output { white-space: pre-wrap; overflow-wrap: anywhere; }
  </style>
</head>
<body>
<p>Compare numeric addition with string concatenation.</p>
  <pre id="output" aria-live="polite"></pre>
  <script>
    const a = 1;
    const b = 2;
    const values = [123, 0, false, null, undefined];
    const lines = [
      `Numeric addition: ${a + b}`,
      `String concatenation: ${String(a) + String(b)}`,
      `Converted type: ${typeof String(a)}`
    ];
    for (const value of values) {
      lines.push(`${typeof value} value → ${JSON.stringify(String(value))}`);
    }
    document.getElementById("output").textContent = lines.join("\n");
  </script>
</body>
</html>

The first two lines show Numeric addition: 3 and String concatenation: 12. The remaining lines include "123", "0", "false", "null" and "undefined". Here, JSON.stringify() adds quotation marks to make the returned strings easier to recognize; it is not required for the conversion itself.

Handle missing values and objects deliberately

If null or undefined should produce no visible text, choose a fallback before converting. The ?? operator uses its right operand only when the left operand is null or undefined, so it preserves valid values such as 0 and false.

const value = null;
const text = String(value ?? "");
console.log(text); // empty string

String({ count: 3 });            // "[object Object]"
JSON.stringify({ count: 3 });    // '{"count":3}'

JSON, or JavaScript Object Notation, is a text format for structured data. Serializing an object with JSON.stringify() can expose its properties more clearly than String(), which commonly produces "[object Object]" for plain objects. JSON serialization has limitations, including circular references. For digit grouping and decimal display options, use number formatting and thousands separators rather than expecting String() to apply a locale.

String() and new String() are different

const primitive = String(123);
const wrapper = new String(123);

typeof primitive;       // "string"
typeof wrapper;         // "object"
primitive === "123";    // true
wrapper === "123";      // false

Call String() without new for ordinary conversion. new String() creates a wrapper object, so its type is object and it is not strictly equal to a primitive string. Strict equality, written ===, compares values without automatically converting their types. To calculate with text again, use Number() conversion and input validation and check that the input is acceptable before using the result.

More in This Category
JavaScript Notes: Number Formatting, URI Encoding and Selectors

JavaScript Notes: Number Formatting, URI Encoding and Selectors

Format numbers, choose the right URI encoding function, and build query parameters safely. Includes decoding error handling, CSS selector guidance and a runnable URL example.

JavaScript Conditionals: if, else if, else and switch

JavaScript Conditionals: if, else if, else and switch

Choose conditional branches with if and switch, understand strict matching and fall-through, and validate input before comparing numbers. Includes a complete browser example.

JavaScript String(): Convert Numbers to Strings

JavaScript String(): Convert Numbers to Strings

Learn how String() converts values, why string concatenation differs from addition, and when null handling or JSON serialization is needed. Compare primitive strings with new String() objects.

JavaScript Thousands Separators: Add Commas and Parse Input

JavaScript Thousands Separators: Add Commas and Parse Input

Format numbers with locale-aware thousands separators and validate grouped decimal input before converting it. Covers decimal options, string formatting and precision limits.

JavaScript Loops: while, do...while and for Compared

JavaScript Loops: while, do...while and for Compared

Compare loop execution order and behavior when the initial condition is false. Learn how break and continue work and avoid infinite loops and index boundary errors.

JavaScript Number(): Convert Strings and Validate Input

JavaScript Number(): Convert Strings and Validate Input

Convert text to numbers while rejecting blank and nonfinite input. Compare Number(), parseInt() and parseFloat(), and account for accepted formats and precision limits.

JavaScript Rounding: Math.floor(), ceil(), round() and trunc()

JavaScript Rounding: Math.floor(), ceil(), round() and trunc()

Compare rounding methods for positive and negative values, round at different positions, and distinguish floating-point arithmetic from toFixed() display formatting.