JavaScript String()
The String() Function
The String() function creates primitive string values.
The new String() Constructor
The new String() constructor creates String objects.
Note
In JavaScript, strings are normally primitive values, not objects.
Function Syntax
String()
String(value)
Constructor Syntax
new String()
new String(value)
Try it Yourself »
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("Hello") |
Returns the primitive string "Hello" |
new String("Hello") |
Returns a String object containing "Hello" |
Primitive Strings
Most JavaScript strings are primitive values.
Primitive strings automatically gain access to String methods when needed.
Note
Use string literals "Hello" instead of new String("Hello").
Common Properties and Methods
lengthcharAt()slice()substring()replace()split()toUpperCase()toLowerCase()
Learn More:
The String() Function
The String() function converts values to primitive strings.
String Objects
The new String() constructor creates a String object.
Example
let text = new String("Hello");
String() vs new String()
String() converts values to primitive strings.
new String() creates String objects.
Example
let x = String("Hello");
let y = new String("Hello");
(typeof x) // string
(typeof y) // object
Try it Yourself »
| Primitive - Recommended | String Object - Rarely needed |
|---|---|
text = "Hello" |
text = new String("Hello") |
| typeof = "string" | typeof = "object" |
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
Try it Yourself »
Warning
Avoid creating String objects. String objects are rarely needed.
Use primitive strings instead.
Use string literals "Hello" instead of
new String("Hello").
Browser Support
String() is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |