Command Palette

Search for a command to run...

Hectal
PHASE 1Beginner ~23 min· topic 4 of 6

Topic 1.4

Strings Basics

In one line

A string is text: a fixed sequence of characters in quotes. You can write it three ways, escape special characters, insert values with template literals, read its length and single characters, but never change it in place.

Think of it like this

A necklace of letter beads. Each bead is one character, and the beads sit in a fixed order. You can count the beads, point at the third one, or make a new necklace with different beads, but this necklace is glued shut: you can't swap a bead on it.

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

String
A piece of text in quotes, like "hello".
Character
One letter, digit, space or symbol inside a string.
Escape
Writing a backslash before a character to give it a special meaning, like \n for a new line.
Template literal
A string in backticks that can insert values with ${ } and span several lines.
Interpolation
Putting the value of an expression inside a string with ${ }.
Expression
Any piece of code that produces a value, like 2 + 3 or name.
Index
The position number of a character. The first one is 0.
length
How many characters (UTF-16 units) a string has.
Immutable
Can't be changed after it's made. Methods give you a new string instead.

Step by step

01Three kinds of quotes

Choose the quote that doesn't appear inside the text, or escape the one that does.

app.jswhole filejavascript
const a = 'She said "hi"';
const b = "It's fine";
const c = 'It\'s fine too';
const d = `Both ' and " are fine here`;

02Escape special characters

A backslash starts an escape sequence. The pair stands for one character.

app.jswhole filejavascript
console.log("Line one\nLine two");
console.log("C:\\Users\\asha");
console.log("Price: \u20B9500");

03Insert values with a template literal

Everything inside ${ } is real code: variables, maths, even function calls. The result is turned into text and placed in the string.

app.jswhole filejavascript
const name = "Asha";
const qty = 3;
console.log(`Hi ${name}, ${qty} items cost ${qty * 250}`);
// Hi Asha, 3 items cost 750

04Count and index

Indexes start at 0, so the last index is always length - 1.

Count and indexdiagram
Rendering diagram…

05Make new strings, never edit old ones

Assigning to an index is silently ignored. To "change" a string, build a new one and reassign the variable (which must be let).

app.jswhole filejavascript
let word = "cat";
word[0] = "b";             // ignored
word = "b" + word.slice(1); // new string "bat"

Try it yourself

  1. 1

    Interpolate maths

    In the template literal example, add a line that logs ` Price with 18% tax: ₹${price * 1.18} `. Predict the number first, then run. Is it what you expected? (Topic 1.3 explains any surprise.)

  2. 2

    Index from the end

    In the length example, log the second-to-last letter twice: once with length and once with at().

  3. 3

    Try to change a letter

    In the last example, add "use strict"; as the very first line and run. Read the error on word[0] = "b": strict mode turns the silent failure into a TypeError.

Code & diagrams

Quotes and escape sequences New tab

`\n` printed as a real line break, so one `console.log` made two lines.

Console

(nothing was printed)

Expected console output

She said "hi"
It's fine
It's fine too
Line one
Line two
C:\Users\asha
Price: ₹500
3
0
Template literals ES2015+ New tab

`${ }` only works inside backticks. In normal quotes it's ordinary text.

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Hi Asha, your 3 items cost ₹750.
Roses are red,
Violets are blue
Is the cart big? false
Not in backticks: ${name}
Length and indexing ES2022+ New tab

`at()` arrived in ES2022. An emoji like 😀 counts as 2 (Topic 4.2 explains why).

Console

(nothing was printed)

Expected console output

6
H
l
l
undefined
2
Strings never change in place New tab

`+=` doesn't edit the string: it builds a new one and points `sentence` at it.

Console

(nothing was printed)

Expected console output

cat
bat
bat BAT
Hello, world

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

Use the same quote inside a string

Write const msg = 'It's here';

terminal
$ Console
── what you'll see ──
Uncaught SyntaxError: Unexpected identifier 's'

Break #2

Expect interpolation in normal quotes

Write const greeting = "Hello, ${name}"; with double quotes.

terminal
$ the page shows
── what you'll see ──
Hello, ${name}

Myth vs fact

Myth

Single and double quotes behave differently, like in PHP or Bash.

Fact

In JavaScript they're identical. Only backticks add interpolation and multi-line text.

Myth

length counts the characters you see.

Fact

It counts UTF-16 code units. Emoji and some other characters use two units, so "😀".length is 2.

Myth

toUpperCase() changes my string.

Fact

Strings are immutable. It returns a new string; the variable still holds the old one unless you reassign it.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    Engines avoid copying when you join strings: V8 builds a rope (a tree of pieces) for repeated +, and flattens it only when needed. So += in a loop is fast in practice; array.join is no longer automatically faster.

  • ▸

    Template literals can be tagged: ` html<p>${x}</p> calls a function that receives the pieces and values separately, which is how libraries escape values safely. String.raw` is a built-in tag that keeps backslashes as written (Topic 14.7).

  • ▸

    Never build HTML from user text with a template literal and innerHTML: it allows cross-site scripting (XSS). Put user text into the page with textContent, as the live example does (Topic 8.3 and 15.4).

  • ▸

    Strings are compared by value, character code by character code: "apple" < "banana" is true, but "Z" < "a" is also true because uppercase letters have smaller codes. Use a.localeCompare(b) for human sorting.

Remember this

  1. 1

    A string is a value made of text. You write it between quotes: single 'hello', double "hello" or backticks ` hello . Single and double quotes behave identically; pick one style and stick to it (most teams use double, or let a formatter like Prettier decide, Topic 12.5). Backticks make a **template literal**, which has extra powers. An **empty string** ""` has no characters at all but is still a string.

  2. 2

    Some characters can't be typed directly inside a string, so you escape them with a backslash \. \" and \' put a quote inside a string that uses the same quote. \n is a newline (line break), \t a tab, and \\ a single real backslash, which you need in Windows paths like "C:\\Users". \u20B9 inserts a character by its Unicode number (here ₹). The backslash and the letter after it count as one character: "a\nb".length is 3.

  3. 3

    Template literals (ES2015) use backticks. Inside them, ${expression} inserts the value of any JavaScript expression (a piece of code that produces a value), turned into text: ` Total: ${qty * price} . This is called **interpolation**, and it replaces long chains of +`. Template literals can also span several lines: the line breaks you type are kept in the string.

  4. 4

    Every string has a length: the number of characters it contains. Characters are numbered from 0, so in "Hectal" the "H" is at index 0 and the last character is at index length - 1. Read one with square brackets: word[0]. An index past the end gives undefined (no error). word.at(-1) (ES2022) counts backwards from the end, so -1 is the last character. Strings can be compared and joined with operators; joining with + is called concatenation (Topic 2.1).

  5. 5

    Strings are immutable. word[0] = "b" does nothing (and in strict mode throws a TypeError). Every string method, like toUpperCase(), returns a new string and leaves the original unchanged, so always store or use the result. let lets you point the name at a new string (word = "b" + word.slice(1)), but the old string itself was never edited.

  6. 6

    One surprise to remember: length counts UTF-16 code units, the 16-bit pieces JavaScript stores text in, not the characters you see. Most letters are one unit, but many emoji take two, so "😀".length is 2. Topic 4.2 explains this fully and shows how to count real characters.

Explain it without notes

01

What is the difference between single quotes, double quotes and backticks?

02

What does it mean that strings are immutable? Give an example.

03

Why is "😀".length equal to 2?

Practice

01

Store a city and a temperature in variables and log It is 31°C in Pune today. using a template literal.

02

Log the first and last character of any word you choose, without typing the index of the last character by hand.

03

Log a two-line address with a single console.log call.

Trade-offs

  • ↔

    Template literals are clearer than + chains for anything with more than one value, but for a plain fixed string, ordinary quotes are simpler and signal that nothing is inserted.

Done when you can

  • I can write strings with single quotes, double quotes and backticks.

  • I can escape quotes, newlines and backslashes.

  • I can insert values with template literals.

  • I can read a string's length and any character by index, including from the end.

  • I can explain why string methods return new strings.