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
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
- Node.js, to run the example. Install it from the Node.js download page (opens in a new tab).
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
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
node to-string.js
42
true
null
string
Each value is printed as text. typeof shows that String(42) gave back a string, not a number.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Calling .toString() on a value that can be null | TypeError: Cannot read properties of null (reading 'toString') | Use String(value), which turns null into "null" |
Expecting String(null) to give empty text | It gives the four letters null | Check 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
- String() constructor (opens in a new tab) (MDN)
- typeof (opens in a new tab) (MDN)
- Run Node.js scripts from the command line (opens in a new tab) (Node.js docs)
JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.
0 comments