JS enginename[0]name[1]name[2]firstnoldloud[0]loud[1]loud[2]msg1const name = "Ada";2const first = name[0];3const n = name.length;4const loud = name.toUpperCase();5const old = name + " has " + n + " letters";6const msg = `${name} has ${n} letters`;7console.log(msg, msg === old);ConsoleAda has 3 letters truestrings.js:7AdaA1233ADA"Ada"" has "3"3"" letters"Ada3Ada has 3 letters true
Back: the JavaScript engine and memory (a string is a row of character boxes, numbered from 0)Front: the script strings.js and the developer consoleTokens: instructions, characters, counters, pieces of text and the finished sentenceAt the back, the JavaScript engine and memory: the string in name is a row of characters, each in a box named by its index. In front, the script strings.js and the developer console. Line 2 reads one character by its index, line 3 counts them, and line 4 builds a new string while name stays the same. Lines 5 and 6 build the same sentence twice, with + and with a template literal, and line 7 prints it and checks they are equal. Strings are immutable. In a module or in strict mode, name[0] = "E" throws a TypeError; in older sloppy scripts it is silently ignored. Either way name still says "Ada".

What a string is

  1. A string is a piece of text: characters in a row, in order. You write one between double quotes "Hi", single quotes 'Hi', or backticks `Hi`. The quotes are not part of the text.

Characters by index

New strings from old

Template literals

What happens

// step 1/8 · text
string    a piece of text: characters in order
write it  "Hi"   'Hi'   `Hi`
          (the quotes are not part of the text)
type      typeof "Hi"  →  "string"
empty     ""  has no characters

Drawing each character in its own box is a simplification: the engine decides how to keep the text in memory. What the language promises is the order, the indexes from 0 and the length. A JavaScript string is really a row of UTF-16 code units, and length counts those. Every letter here takes one, but some characters take two: "😀".length is 2.