JavaScript String Primitive
A string primitive represents text.
The type name is string.
String values are one of JavaScript's 7 primitive types.
Creating Strings
Strings can be created with single quotes, double quotes, or backticks.
Type Information
The type of a primitive string value is "string".
String Length
The length of a string is the number of characters it contains.
String Characters
Characters can be accessed by index.
The first character has index 0.
Strings Are Iterable
String values are iterable.
They can be used in for...of loops.
Primitive Strings vs String Objects
A string literal creates a primitive string.
The new String() constructor creates a String object.
| Primitive - Recommended | String Object - Rarely needed |
|---|---|
let text = "Hello" |
let text new String("Hello") |
typeof text === "string" |
typeof text === "object" |
Example
let a = "Hello";
let b = new String("Hello");
(typeof a) // string
(typeof b) // object
Try it Yourself »
String Methods
Primitive strings can use String methods.
JavaScript temporarily wraps the primitive value in a String object when a method is called.
String Conversion
The String() function converts values to strings.
| Expression | Result |
|---|---|
String(123) |
"123" |
String(true) |
"true" |
String(null) |
"null" |