Chapter III · Data Types

Strings

The string data type represents textual data, stored as sequences of UTF-16 code units.

01 What are Strings?

A string is used to represent text in JavaScript. Strings can be enclosed in single quotes ('), double quotes ("), or backticks (`) for template literals.

Strings are immutable primitives. Once a string is created, its individual characters cannot be modified in place.

02 Simple Example

Creating strings and using template literals for interpolation.

strings.js
const firstName = "JavaScript";
const greeting = `Hello, ${firstName}!`;
console.log(greeting); // "Hello, JavaScript!"
console.log(greeting.length); // 18

Template literals allow embedding expressions directly inside backticks using ${} syntax.

03 How It Works

Strings are indexed collections of 16-bit code units. You can access characters by numeric indices, though methods like slice() or concat() always return brand new string primitives.

Variable Reference Primitive Value

Strings are immutable indexed sequences of character code units.

04 Step-by-Step

  1. String literals are parsed into immutable UTF-16 character sequences.

  2. Methods or property lookups access character elements or return derived strings.

  3. Reassignment or transformation yields a new string value in memory.

05 Mental Model

"A printed strip of paper with words stamped on it."

To change a word, you don't erase the ink; you print a brand-new strip of paper.

06 Interview Questions

Q: How do you check if a string contains a substring?

String.prototype.includes() — cleaner than the older indexOf(...) !== -1 pattern.

Q: Why are template literals generally preferred over string concatenation?

They embed expressions directly with ${...}, support multi-line strings natively, and avoid the readability cost of chained + operators.

Key Takeaway

Strings are immutable primitive sequences of text characters supporting powerful built-in manipulation methods and template interpolation.

Related Concepts