cf.completefrontendCode editorOpen lab
THE JAVASCRIPT FIELD GUIDE

Strings

Create JavaScript text with quotes and template literals, use escape sequences, read characters by index, and understand why strings are immutable.

By the end, you can
  • 01
    Create text safelyChoose single quotes, double quotes, backticks, and escapes on purpose.
  • 02
    Inspect charactersUse length, indexes, and at(-1) without off-by-one surprises.
  • 03
    Build 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.

Definition

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.

Real-life analogyA string is a bead necklace

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 THROUGH

JavaScript 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}.

Three ways to write string literals
FormExampleBest use
Single quotes'hello'Short text with no apostrophe, or teams that prefer this style.
Double quotes"I'm learning"Text that contains apostrophes.
BackticksHi, ${name}Fill-in-the-blank strings, multi-line text, and expressions like ${price * qty}.
Real-life analogyA template literal is a fill-in-the-blank form

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.

Compare concatenation and a template literal
Step 0 of 8Ready
Your turn: follow the blue line

Predict whether line 7 and line 8 print the same text. Then step through the quote styles and interpolation.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
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);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Change lines 1 and 2, then predict lines 7 and 8

Changing the person restarts the replay with real new values.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

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

INTERACTIVE

An 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.

Common string escape sequences
EscapeProducesExample use
\nNew line"Line 1\nLine 2"
\tTab"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}"
Decode escape sequences
Step 0 of 5Ready
Your turn: follow the blue line

Step through real escape sequences. Notice that the two characters \n become an actual line break in the first output.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
console.log("Name\tScore");console.log("She said \"hi\"");console.log("C:\\notes");console.log("Smile: \u{1F600}");
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

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

INTERACTIVE

Strings 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.

Live string inspector
The inspected operationsPop out in the code editor (opens in a new tab)JavaScript
const text = "JavaScript";console.log(text.length);console.log(text[0]);console.log(text.at(-1));console.log(text[99]);
Computed now10 positions
text.length10
text[0]J
text.at(-1)t
text[text.length - 1]t
text[99]undefined
0J
1a
2v
3a
4S
5c
6r
7i
8p
9t
Try it yourself

The current string has length 10. Index 0 is J, the last index is length - 1, and index 99 is undefined.

Every value here is computed from the text you type. Some emoji use two JavaScript string positions; the Unicode & string internals lesson explains why.

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.

Emoji note

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 THROUGH

Strings 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.

Real-life analogyA string is carved in stone

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:

Sloppy script: assignment ignoredPop out in the code editor (opens in a new tab)JavaScript
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:

Strict mode: assignment throwsPop out in the code editor (opens in a new tab)JavaScript
"use strict";let word = "cat";word[0] = "b";console.log(word);
Fix a string without editing a character
Step 0 of 4Ready
Your turn: follow the blue line

The failed edit is not shown here. This is the safe fix: create a new string, then reassign the variable.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
word = "b" + word.slice(1);console.log(word);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
Why slice appears here

This 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 THROUGH

Concatenation means joining strings. The + operator joins when either side is a string. += is the “join onto the existing value” shortcut, common in small loops.

Build text with + and +=
Step 0 of 10Ready
Your turn: follow the blue line

Watch += build a sentence, then compare the two Total lines.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
for (let i = 1; i <= 3; i = i + 1) {  message += "#" + i + " ";}console.log(message);console.log("Total: " + 2 + 3);console.log("Total: " + (2 + 3));
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

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).

Teaser: arrays can join too

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.

Practical string buildingPop out in the code editor (opens in a new tab)JavaScript
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.

Valid string or syntax error?
  • 'It's fine'
  • "It's fine"
  • `It's fine`
  • 'Say \"hi\"'
  • "hello
  • 'line 1 line 2'
Try it yourself
0 of 6 correct

Sort each snippet. The explanations show how quote choice and escaping affect parsing.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Practice: strings

5 EXERCISES
Exercise 1 · Warm-upPredict length and indexes

Predict the four console outputs.

Starter codePop out in the code editor (opens in a new tab)JavaScript
const text = "Hi!";
console.log(text.length);
console.log(text[0]);
console.log(text[text.length - 1]);
console.log(text[99]);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeBuild a greeting with a template literal

    Read the code and type the exact sentence it prints.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const name = "Ada";
    const place = "console";
    console.log(`Hello, ${name}! Welcome to the ${place}.`);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeEscape a quote correctly

      What text does this program print?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      console.log("She said \\"JavaScript!\\"");

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · ChallengeFix the character-changing bug

        Rewrite the code so it prints bat.

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        let word = "cat";
        word[0] = "b";
        console.log(word);

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · PracticePredict concatenation order

          Predict the exact output.

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          console.log("Total: " + 2 + 3);

          Answer, then press Check. Spacing and letter case don’t matter.

            Quiz: check your understanding

            7 QUESTIONS
            Lesson quiz · 7 questionsScore: first tries count
            1. Question 1 of 7Which quote style lets you write ${name} interpolation?

              Choose an answer to see the explanation.

            2. Question 2 of 7What length does this print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const word = "cat";
              console.log(word.length);

              Choose an answer to see the explanation.

            3. Question 3 of 7What character does this print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const word = "cat";
              console.log(word[0]);

              Choose an answer to see the explanation.

            4. Question 4 of 7What does \n mean inside a normal string literal?

              Choose an answer to see the explanation.

            5. Question 5 of 7What does this sloppy classic script print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              let word = "cat";
              word[0] = "b";
              console.log(word);

              Choose an answer to see the explanation.

            6. Question 6 of 7What total text does this print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log("Total: " + 2 + 3);

              Choose an answer to see the explanation.

            7. 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.
            • length counts string positions, indexes start at 0, and missing indexes read as undefined.
            • 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.

            CompleteFrontend Clear concepts. Working examples.