The String()
constructor creates String
objects. When called as a function, it returns primitive values of type String.
The String()
constructor creates String
objects. When called as a function, it returns primitive values of type String.
new String(thing) String(thing)
Note: String()
can be called with or without new
, but with different effects. See Return value.
thing
Anything to be converted to a string.
When String
is called as a constructor (with new
), it creates a String
object, which is not a primitive.
When String
is called as a function, it coerces the parameter to a string primitive. Symbol values would be converted to "Symbol(description)"
, where description
is the description of the Symbol, instead of throwing.
Warning: You should rarely find yourself using String
as a constructor.
String function and String constructor produce different results:
const a = new String("Hello world"); // a === "Hello world" is false const b = String("Hello world"); // b === "Hello world" is true a instanceof String; // is true b instanceof String; // is false typeof a; // "object" typeof b; // "string"
Here, the function produces a string (the primitive type) as promised. However, the constructor produces an instance of the type String (an object wrapper) and that's why you rarely want to use the String constructor at all.
String()
is the only case where a symbol can be converted to a string without throwing, because it's very explicit.
const sym = Symbol("example"); `${sym}`; // TypeError: Cannot convert a Symbol value to a string "" + sym; // TypeError: Cannot convert a Symbol value to a string "".concat(sym); // TypeError: Cannot convert a Symbol value to a string
const sym = Symbol("example"); String(sym); // "Symbol(example)"
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Opera | Safari | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | WebView Android | Deno | Node.js | ||
String |
1 | 12 | 1 | 3 | 1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 | 1.0 | 0.10.0 |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String