Strings
Create JavaScript text with quotes and template literals, use escape sequences, read characters by index, and understand why strings are immutable.
- 01Create text safelyChoose single quotes, double quotes, backticks, and escapes on purpose.
- 02Inspect charactersUse
length, indexes, andat(-1)without off-by-one surprises. - 03Build new stringsUse
+,+=, and template literals while remembering strings are immutable.
Strings are JavaScript text
A string is a value that stores text: a name, a message, a file path, a button label, or the answer that prompt gives back. Strings are primitives, like you saw in the Data types lesson, which means the value itself is simple and immutable.
You have already seen JavaScript do something surprising with strings: "5" + 3 becomes "53" in Why JavaScript?. This lesson slows down and explains the text side of that rule before the Type conversion lesson gives the full conversion table.
A JavaScript string is an ordered sequence of character positions, written with quotes or backticks, read by zero-based indexes, and changed only by creating a new string.
Imagine the text as beads on a necklace. The first bead is numbered 0, the next is 1, and so on. You can point at a bead, count the beads, or make a new necklace with different beads.
- In real life: The whole necklace
- In JavaScript: The whole string, like
"cat" - In real life: One bead
- In JavaScript: One character position, like
word[0] - In real life: Numbering beads from the clasp
- In JavaScript: Indexes starting at 0
- In real life: Counting all beads
- In JavaScript:
word.length
Where the analogy stops: JavaScript strings count UTF-16 code units, not human-perceived letters. Most beginner examples match one character per position, but some emoji take two positions.
We will cover quotes and template literals, escape sequences, length and indexing, immutability, and concatenation in that order. Later lessons named String methods, Template literals & tagged templates, Unicode & string internals, and Comparing & sorting text go deeper.
Quotes & template literals
STEP THROUGHJavaScript gives you three common ways to write string literals. Single quotes and double quotes are the same kind of string; choose whichever makes the text easier to read. Backticks create a template literal, which can span lines and fill blanks with $${expression}.
| Form | Example | Best use |
|---|---|---|
| Single quotes | 'hello' | Short text with no apostrophe, or teams that prefer this style. |
| Double quotes | "I'm learning" | Text that contains apostrophes. |
| Backticks | Hi, ${name} | Fill-in-the-blank strings, multi-line text, and expressions like ${price * qty}. |
Think of a template literal as a tiny Mad Libs card. The fixed words are already printed, and JavaScript fills each blank by running the expression inside $${...}.
- In real life: A blank labeled name
- In JavaScript:
${name} - In real life: A blank that asks for a calculation
- In JavaScript:
${price * qty} - In real life: The completed form
- In JavaScript: The final string value
Where the analogy stops: A paper form waits for a person. JavaScript fills the blanks immediately when that line runs. Tagged templates are a later lesson with extra processing rules.
In this replay, line 5 uses a template literal and line 6 uses old-fashioned concatenation. Change the person and predict whether the two printed lines still match.
Predict whether line 7 and line 8 print the same text. Then step through the quote styles and interpolation.
script
const age = 12;const single = 'A string can use single quotes.';const double = "Double quotes make apostrophes easy: I'm learning.";const template = `Hi, ${name}. Next year you will be ${age + 1}.`;const same = "Hi, " + name + ". Next year you will be " + (age + 1) + ".";console.log(template);console.log(same);Backticks are often clearer for sentences because the variable names sit where the values appear. Concatenation is still useful for short pieces and for gradually building a string.
Escape sequences
INTERACTIVEAn escape sequence is a backslash code inside a string. It says, “Do not read the next character normally.” For example, \n means put a line break here, and \" means include a quote mark instead of ending the string.
| Escape | Produces | Example use |
|---|---|---|
\n | New line | "Line 1\nLine 2" |
\t | Tab | "Name\tScore" |
\\ | One backslash | "C:\\notes" |
\' | Single quote | 'It\'s ok' |
\" | Double quote | "She said \"hi\"" |
\` | Backtick | `Use \`code\`` |
\u{1F600} | A 😀 character | "Smile: \u{1F600}" |
Step through real escape sequences. Notice that the two characters \n become an actual line break in the first output.
script
console.log("Name\tScore");console.log("She said \"hi\"");console.log("C:\\notes");console.log("Smile: \u{1F600}");Use escapes when they make the string easier to write. If escaping gets noisy, switch quote styles or use a template literal. For example, "It's ok" is easier than 'It\'s ok'.
Length & indexing
INTERACTIVEStrings are ordered. text.length tells you how many string positions there are. Bracket indexing reads one position: text[0] is the first position, and text[text.length - 1] is the last position when the string is not empty.
const text = "JavaScript";console.log(text.length);console.log(text[0]);console.log(text.at(-1));console.log(text[99]);The current string has length 10. Index 0 is J, the last index is length - 1, and index 99 is undefined.
If you ask for a position that does not exist, JavaScript gives undefined. That is the same “no value here” word you will study in the next lesson, Booleans, null & undefined.
Try 😀 in the inspector. In JavaScript, "😀".length is 2 because strings count UTF-16 code units. That is not a beginner mistake; it is a real language detail saved for the Unicode & string internals lesson.
Strings are immutable
STEP THROUGHStrings are primitive values, and primitive strings are immutable: you cannot edit one character in place. A variable can point to a different string later, but the original string value does not get patched.
If word labels a carved stone that says “cat,” you cannot replace only the first letter. You carve a new stone that says “bat,” then move the word label to it.
- In real life: A word carved into a stone
- In JavaScript: The string value
"cat" - In real life: Trying to scratch out one letter
- In JavaScript:
word[0] = "b" - In real life: Carving a new stone
- In JavaScript:
"b" + word.slice(1) - In real life: Moving the label to the new stone
- In JavaScript:
word = ...
Where the analogy stops: Computers do store strings in memory, not stone. The point is that JavaScript does not let your code mutate a string's character positions.
Here is the tempting but wrong edit in a classic sloppy script:
let word = "cat";word[0] = "b";console.log(word);It prints cat. In strict mode, including JavaScript modules and code that starts with "use strict", the same assignment throws a TypeError instead of being silently ignored:
"use strict";let word = "cat";word[0] = "b";console.log(word);The failed edit is not shown here. This is the safe fix: create a new string, then reassign the variable.
script
word = "b" + word.slice(1);console.log(word);slice appears hereThis lesson is not about string methods yet. We use the simple method slice(1) only to copy “everything after the first character.” The full String methods lesson covers it properly.
Concatenation
STEP THROUGHConcatenation means joining strings. The + operator joins when either side is a string. += is the “join onto the existing value” shortcut, common in small loops.
Watch += build a sentence, then compare the two Total lines.
script
for (let i = 1; i <= 3; i = i + 1) { message += "#" + i + " ";}console.log(message);console.log("Total: " + 2 + 3);console.log("Total: " + (2 + 3));The most important beginner trap is order. "Total: " + 2 + 3 starts with a string, so it joins left to right and produces "Total: 23". Add parentheses when you mean math first: "Total: " + (2 + 3).
For long lists of pieces, code often collects pieces in an array and uses join(""). Arrays and String methods get their own later lessons, so for now focus on +, +=, and template literals.
Where you’ll use this
Strings show up whenever code talks to humans or other systems. You will use them to build labels, read form input, create URLs, print debug messages, and combine values in UI text.
const user = "Ada";const unread = 3;const label = `${user} (${unread} new messages)`;console.log(label); const path = "/users/" + user;console.log(path);Notice the split: template literals read like sentences, while + is fine for short mechanical pieces like a URL path. When values come from prompt, remember the result is already a string.
Common misconceptions
“Single quotes and double quotes create different types.”
They create the same string type. Style and escaping convenience are the difference.
“Indexes start at 1 because humans count that way.”
JavaScript string indexes start at 0. The last index is length - 1.
“Changing word[0] changes the string.”
It does not. Sloppy scripts ignore it; strict code throws. Create a new string instead.
“+ always means arithmetic.”
With a string involved, + concatenates. Parenthesize math you want to happen first.
“length always means visible letters.”
For basic English examples, yes. For some emoji and combined characters, not always; Unicode gets its own lesson.
'It's fine'"It's fine"`It's fine`'Say \"hi\"'"hello'line 1 line 2'
Sort each snippet. The explanations show how quote choice and escaping affect parsing.
Practice: strings
5 EXERCISESPredict the four console outputs.
const text = "Hi!";
console.log(text.length);
console.log(text[0]);
console.log(text[text.length - 1]);
console.log(text[99]);length is 3. Index 0 is H; length - 1 is 2, so the last character is !; index 99 does not exist, so it prints undefined.
Read the code and type the exact sentence it prints.
const name = "Ada";
const place = "console";
console.log(`Hello, ${name}! Welcome to the ${place}.`);const name = "Ada";
const place = "console";
console.log(`Hello, ${name}! Welcome to the ${place}.`);The template literal fills the two blanks, so the console prints Hello, Ada! Welcome to the console.
What text does this program print?
console.log("She said \\"JavaScript!\\"");console.log("She said \\"JavaScript!\\"");The backslashes keep the inner double quotes from ending the string. They do not appear in the final output.
Rewrite the code so it prints bat.
let word = "cat";
word[0] = "b";
console.log(word);let word = "cat";
word = "b" + word.slice(1);
console.log(word);Strings are immutable, so the fix creates bat as a new string and reassigns the variable word.
Predict the exact output.
console.log("Total: " + 2 + 3);First "Total: " + 2 becomes "Total: 2". Then + 3 joins again, so the output is Total: 23.
Quiz: check your understanding
7 QUESTIONSQuestion 1 of 7Which quote style lets you write
${name}interpolation?Choose an answer to see the explanation.
Question 2 of 7What length does this print?
Read the code, then predictconst word = "cat"; console.log(word.length);Choose an answer to see the explanation.
Question 3 of 7What character does this print?
Read the code, then predictconst word = "cat"; console.log(word[0]);Choose an answer to see the explanation.
Question 4 of 7What does
\nmean inside a normal string literal?Choose an answer to see the explanation.
Question 5 of 7What does this sloppy classic script print?
Read the code, then predictlet word = "cat"; word[0] = "b"; console.log(word);Choose an answer to see the explanation.
Question 6 of 7What total text does this print?
Read the code, then predictconsole.log("Total: " + 2 + 3);Choose an answer to see the explanation.
Question 7 of 7Which expression reads the last character of a non-empty string named
text?Choose an answer to see the explanation.
Key takeaways
- Strings store text and are written with single quotes, double quotes, or backticks.
- Template literals use
$${...}to insert expression results. - Escape sequences such as
\n,\t, and\"put special characters inside strings. lengthcounts string positions, indexes start at 0, and missing indexes read asundefined.- Strings are immutable; make a new string and reassign the variable when text needs to change.
+and+=concatenate strings; use parentheses when you need math first.
Remember the one-liner.
A string is immutable JavaScript text: create it with quotes or backticks, read positions from 0, and build new strings when the text changes.
Up next: Booleans & truthiness, then undefined and null.