Photo by PJH on Unsplash

On this page

This chapter follows Numbers and BigInt.

The string primitive stores text. Once created, a string’s contents do not change; methods such as slice and toUpperCase return new strings. The engine may intern or share storage, but the language model is immutable value semantics as described in Pass by value and reference.

Creating strings

Single and double quotes behave the same. Backticks introduce template literals:

const name = "Ada";
const greeting = `Hello, ${name}!`;

Escape sequences (\n, \u{1F600}, and others) work in all three quote styles. Template literals can span lines without concatenation.

UTF-16 code units versus code points

Strings are indexed by UTF-16 code unit, not by Unicode code point. Characters outside the Basic Multilingual Plane (many emoji) occupy two code units (a surrogate pair).

"😀".length; // 2
[..."😀"].length; // 1 — spread iterates code points

Use String.prototype.codePointAt, the u flag on regular expressions, or iteration with spread when you need code-point-aware length or slicing.

Common methods and coercions

Strings expose a large prototype API: includes, startsWith, padStart, replace, split, and locale-aware localeCompare via Intl.

When a primitive string is used like an object, the engine boxes it briefly so methods exist:

" hi ".trim(); // "hi"

Concatenation with + converts the non-string side with ToString when neither side is already a string in the sense of the + algorithm — see Type coercion and equality.

Template literal features

Beyond ${expression}, templates support raw strings via String.raw and tagged templates:

function sql(strings, ...values) {
// build a parameterized query from strings and values
return { text: strings.join("?"), values };
}
const id = 42;
sql`SELECT * FROM users WHERE id = ${id}`;

Tags receive an array of literal segments and the evaluated expressions. They are useful for embedded DSLs (SQL, HTML builders, i18n) when you validate or escape values inside the tag.

Comparison and sorting

=== compares string contents. < and > use lexicographic order of code units, which is not always the collation order a user expects for natural language. Use Intl.Collator for locale-aware sorting in UI lists.

String conversion at boundaries

String(value) and template interpolation call ToString. Objects default to "[object Object]" unless they define toString. Arrays join elements with commas, which is why [1, 2] + [3] becomes "1,23" in JavaScript Fails.

At API boundaries, be explicit: JSON.stringify for data, String for logging, and dedicated serializers for dates and bigints.

Next: Symbols in JavaScript.

Search articles

Type a word to search published articles.

Open the search page