Strings
A string is a sequence of characters used to represent text: a student's name, an email address, a line on a receipt. JavaScript strings are written between quotes, are immutable (every change creates a new string), and are stored internally as UTF-16 code units, a detail that explains why some emoji have a length of 2. This lesson covers creating, reading and combining strings; the next three cover template literals, string methods and searching.
In One Minute
- Write strings with
"double",'single'or`backtick`quotes. Backticks (template literals) allow${}and line breaks. - Escape special characters with a backslash:
\n(new line),\",\',\\. str.lengthcounts UTF-16 code units;str[0]andstr.at(-1)read single characters.- Strings are immutable: methods return new strings and never change the original.
- Emoji and some rare characters take two code units, so
"😀".lengthis 2. Use[...str]to count real characters.
Creating Strings
const first = "Navika";
const last = 'Anamaneni';
const city = `Dallas`;
const full = first + " " + last;
console.log(full);
console.log(`${first} lives in ${city}.`);
console.log(typeof full);Navika Anamaneni
Navika lives in Dallas.
string| Quotes | Example | Notes |
|---|---|---|
Double " | "It's due" | Can contain ' without escaping |
Single ' | 'Say "paid"' | Can contain " without escaping |
Backticks ` | `Total: ${fee}` | Template literal: ${} and multiple lines |
Double and single quotes behave identically; pick one style per project (a formatter such as Prettier enforces it). This course uses double quotes for plain strings.
Escape Sequences
A backslash \ inside a string starts an escape sequence: a way to write a character that would otherwise end the string or can't be typed.
| Sequence | Character |
|---|---|
\" and \' | A quote that doesn't end the string |
\\ | A backslash |
\n | New line |
\t | Tab |
\u00e9 or \u{1F600} | A Unicode character by its code (é, a smiling face) |
console.log("She said \"paid in full\".");
console.log('It\'s due Friday.');
console.log("Line one\nLine two");
console.log("C:\\fees\\2026");
console.log("Caf\u00e9");She said "paid in full".
It's due Friday.
Line one
Line two
C:\fees\2026
CaféLength and Characters
length is a property (no parentheses) that gives the number of UTF-16 code units, which for ordinary text is the number of characters. Characters are numbered from 0:
const name = "Srihitha";
console.log(name.length);
console.log(name[0]);
console.log(name[name.length - 1]);
console.log(name.at(-1));
console.log(name.at(-2));
console.log(name[20]);8
S
a
a
h
undefinedExplanation: name[0] is the first character. The last one is at length - 1. The newer at() method accepts negative numbers that count from the end, so at(-1) is the last character, which reads more clearly. Reading past the end gives undefined, not an error.
Strings Are Immutable
Immutable means a string's characters can never be changed after it is created. Assigning to an index silently does nothing (and throws in strict mode), and every string method returns a new string:
let name = "navika";
name[0] = "N"; // ignored: strings can't be changed
console.log(name);
const upper = name.toUpperCase();
console.log(upper);
console.log(name); // the original is unchanged
name = name[0].toUpperCase() + name.slice(1); // build a new string
console.log(name);navika
NAVIKA
navika
NavikaJoining Strings
Three ways to combine text:
const name = "Advitha";
const fee = 95;
console.log("Fee for " + name + ": $" + fee);
console.log(`Fee for ${name}: $${fee}`);
console.log(["Navika", "Srihitha", "Advitha"].join(", "));Fee for Advitha: $95
Fee for Advitha: $95
Navika, Srihitha, AdvithaTemplate literals (the second line) are the modern default: easier to read and no missing-space bugs. join is best for lists. Building a long string piece by piece in a loop with += is fine in modern engines.
In Practice
The Fee Tracker cleans up a name typed into a form and builds a display label with initials:
function displayLabel(rawName) {
const name = rawName.trim();
const parts = name.split(" ");
const initials = parts.map((p) => p[0].toUpperCase()).join("");
return `${name} (${initials})`;
}
console.log(displayLabel(" Navika Anamaneni "));
console.log(displayLabel("srihitha anamaneni"));Navika Anamaneni (NA)
srihitha anamaneni (SA)trim, split and toUpperCase are string methods, covered fully in the string methods lesson; map is an array method from the arrays chapter.
Common Mistakes
Mismatched quotes. "It's" is fine, but 'It's' ends at the second '. Use the other quote type, escape it, or use backticks.
Expecting methods to change the string. name.toUpperCase(); alone does nothing useful. Assign the result.
Using length for user-visible limits with emoji. It counts code units. Use [...str].length or Intl.Segmenter.
Reading str.length(). length is a property, not a method: TypeError: str.length is not a function.
Under the Hood
JavaScript strings are sequences of 16-bit code units (the UTF-16 encoding). Most characters you meet (English, accented letters, Chinese, Hindi) fit in one code unit. Characters with codes above 65,535, which include emoji and rare scripts, are stored as two code units called a surrogate pair. length, str[i] and slice all count code units, not characters:
const face = "😀";
console.log(face.length);
console.log([...face].length);
const label = "Paid 👍";
console.log(label.length);
console.log([...label].length);
console.log(label.codePointAt(5).toString(16));2
1
7
6
1f44dExplanation: the smiling-face emoji has the code point U+1F600, which needs two UTF-16 units, so its length is 2. Spreading a string into an array with [...str] (or looping with for...of) iterates by code point, which is what people mean by "characters". codePointAt gives the full code: 1f44d is the thumbs-up.
Even code points aren't the whole story: some visible symbols are several code points joined together, such as a family emoji or a flag. For counting what a person sees as one character (a grapheme), use Intl.Segmenter:
const family = "👨👩👧";
console.log(family.length, [...family].length);
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
console.log([...segmenter.segment(family)].length);8 5
1Interview Corner
Are JavaScript strings mutable?
No. Strings are immutable primitives. Index assignment is ignored (a TypeError in strict mode), and every method returns a new string. Reassigning a variable (s = s + "x") points it at a new string; it doesn't modify the old one.
Why does an emoji have a length of 2?
JavaScript strings are UTF-16 code unit sequences. Code points above U+FFFF are encoded as surrogate pairs (two code units), and length counts code units. Use [...str].length for code points, or Intl.Segmenter for user-perceived characters (grapheme clusters).
Practice
Challenge: Write shorten(text, max) that returns text unchanged if it has at most max code points, or otherwise the first max - 1 code points plus "…". It must not break an emoji.
Show solution
function shorten(text, max) {
const chars = [...text];
if (chars.length <= max) return text;
return chars.slice(0, max - 1).join("") + "…";
}
console.log(shorten("Navika", 10));
console.log(shorten("Advitha Anamaneni", 8));
console.log(shorten("Paid 👍👍👍", 7));Navika
Advitha…
Paid 👍…Key Takeaways
| Task | Code |
|---|---|
| Length | str.length |
| First / last character | str[0], str.at(-1) |
| Join with values | `Hi ${name}` |
| Join a list | arr.join(", ") |
| Count code points | [...str].length |
Was this tutorial helpful?