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()
String(value)
new String()
new String(value)
Parameters
| Parameter | Description |
|---|---|
| value | Optional. A value to convert to a string. |
Return Value
| Call | Returns |
|---|---|
String(value) |
A primitive string |
new String(value) |
A String object |
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();
Common Properties and Methods
lengthcharAt()slice()substring()replace()split()toUpperCase()toLowerCase()
String Objects
The new String() constructor creates a String object.
Example
let text = new String("Hello");
Warning
Avoid creating String objects.
String objects are rarely needed.
Use primitive strings instead.
Use string literals or String() conversions instead of
new String().
String() vs new String()
Calling String() converts a value to a primitive string.
Calling new String() creates a String object.
Example
let a = String(123);
let b = new String(123);
(typeof x) // string
(typeof y) // object
| Primitive String | String Object |
|---|---|
text = "Hello" |
text = new String("Hello") |
| typeof = string | typeof = object |
| Recommended | Rarely needed |
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
Object Hierarchy
String objects inherit from Object.
Object └─ String
| What | Value |
|---|---|
| Constructor Type | Function |
| Creates | Primitive strings or String objects |
| Inherits From | Object (for String objects) |
| Primitive Type | string |
Use string literals or String() conversions instead of new String().
Example
let a = "John";
let b = new String("John");
(a === b) //false
Browser Support
String() is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |