Strings

Updated · 7 min read
easyES2026javascriptstringsunicodeutf-16interview

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.length counts UTF-16 code units; str[0] and str.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 "😀".length is 2. Use [...str] to count real characters.

Creating Strings

create.js▶ Try it
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);
Output
Navika Anamaneni
Navika lives in Dallas.
string
QuotesExampleNotes
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.

SequenceCharacter
\" and \'A quote that doesn't end the string
\\A backslash
\nNew line
\tTab
\u00e9 or \u{1F600}A Unicode character by its code (é, a smiling face)
escapes.js▶ Try it
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");
Output
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:

index.js▶ Try it
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]);
Output
8
S
a
a
h
undefined

Explanation: 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:

immutable.js▶ Try it
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);
Output
navika
NAVIKA
navika
Navika

Joining Strings

Three ways to combine text:

join.js▶ Try it
const name = "Advitha";
const fee = 95;
 
console.log("Fee for " + name + ": $" + fee);
console.log(`Fee for ${name}: $${fee}`);
console.log(["Navika", "Srihitha", "Advitha"].join(", "));
Output
Fee for Advitha: $95
Fee for Advitha: $95
Navika, Srihitha, Advitha

Template 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:

label.js▶ Try it
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"));
Output
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:

utf16.js▶ Try it
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));
Output
2
1
7
6
1f44d

Explanation: 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:

graphemes.js▶ Try it
const family = "👨‍👩‍👧";
console.log(family.length, [...family].length);
 
const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
console.log([...segmenter.segment(family)].length);
Output
8 5
1

Interview 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
shorten.js▶ Try it
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));
Output
Navika
Advitha…
Paid 👍…

Quick check: Strings

3 questions
1What does "Fee".at(-1) return?
2What does name.toUpperCase() do to name?
3Why can "👍".length be 2?

Key Takeaways

TaskCode
Lengthstr.length
First / last characterstr[0], str.at(-1)
Join with values`Hi ${name}`
Join a listarr.join(", ")
Count code points[...str].length

Was this tutorial helpful?

Lesson 19 of 139