JavaScript String()
The String() constructor creates string values or String objects.
In JavaScript, strings are normally primitive values, not objects.
The new String() constructor creates a String object.
Syntax
String(value)
new String(value)
Parameters
| Parameter | Description |
|---|---|
| value | Optional. A value to convert to a string. |
Explained
| Expression | Result |
|---|---|
String(123) |
Returns the primitive string "123" |
new String(123) |
Returns a String object containing "123" |
Example
let x = String(123);
let y = new String(123);
(typeof x) // string
(typeof y) // object
Primitive Strings
Most JavaScript strings are primitive values.
Primitive strings automatically gain access to String methods when needed.
Example
let text = "Hello";
text.toUpperCase();
String Objects
The new String() constructor creates a String object.
String objects are rarely needed.
Use primitive strings instead.
Example
let text = new String("Hello");
Warning
Avoid creating String objects.
Use string literals or String() conversions instead of
new String().
Primitive Values vs Wrapper Objects
String() is actually one of the best examples to understand the difference between primitive values and wrapper objects, which is a central part of JavaScript's type system and often not very visible in a JavaScript Reference.
Example
let a = "John";
let b = new String("John");
(a == b); // true
(a === b); // false
Return Values
| Call | Returns |
|---|---|
String(value) |
A primitive string |
new String(value) |
A String object |
Browser Support
new String() is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |