Skip to main content
0 reactions

How to Convert a Value to a String with String() in JavaScript

A card titled String() in JavaScript, labelled JavaScript Basics, showing String(42), String(true) and String(null) turned into text, and typeof giving string.
String() in JavaScript: Turn any value into text, even null.

String() turns a value into a string, JavaScript’s type for text. It works on every value, even null and undefined, which makes it a safe way to get text from a value you’re not sure about.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

SyntaxJavaScript
String(value)
  • String: a built-in function, with a capital S.
  • value: any value. String() gives it back as text.

See String() constructor (opens in a new tab) on MDN.

Prerequisites

The Example

Three values of different types, a number, true and null, turned into text, plus a check of what String() gives back. The file is to-string.js.

Step 1: Write the Code

to-string.jsJavaScript
console.log(String(42));
console.log(String(true));
console.log(String(null));
console.log(typeof String(42));

The last line uses typeof, which gives the name of a value’s type.

Step 2: Run It

TerminalBash
node to-string.js
OutputPlain text
42
true
null
string

Each value is printed as text. typeof shows that String(42) gave back a string, not a number.

Common Mistakes

MistakeWhat happensDo this instead
Calling .toString() on a value that can be nullTypeError: Cannot read properties of null (reading 'toString')Use String(value), which turns null into "null"
Expecting String(null) to give empty textIt gives the four letters nullCheck for null first if empty text is what you want
Writing new String(42)You get an object wrapper: typeof new String(42) is "object"Call String(42) without new

FAQ

What does String() do with objects and arrays?

An object becomes [object Object], and an array becomes its items joined by commas: String([1, 2]) is 1,2.

Conclusion

String(value) turns any value into text without crashing on null or undefined. Check for those first when their names shouldn’t end up in your text.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

0 comments