Strings and template literals
A string is text: a row of characters in order, each at an index that starts at 0. Follow a seven-line script as it stores "Ada", reads one character, counts the characters, builds an upper-case copy while the original stays the same, and makes the sentence "Ada has 3 letters" twice: once by gluing pieces with + and once with a template literal.
5 quick questions
Pick an answer to see why. Your score saves with your progress.
01const word = "cat"; What is word[1]?
Indexes start at 0, so word[0] is "c", word[1] is "a" and word[2] is "t".
02const word = "cat"; What are word.length and the last index?
length counts the characters: 3. Counting starts at 0, so the last index is always length minus 1: 2.
03const name = "Ada"; const loud = name.toUpperCase(); What is in name afterwards?
Strings never change. toUpperCase() builds a new string, "ADA", which goes into loud; name still holds "Ada".
04const n = 3; What does `I have ${n} cats` give?
In a template literal (backticks), each ${...} slot is replaced by the value inside, turned into text.
05What does "Hi" + "there" give?
+ joins strings end to end and adds no spaces. Write "Hi " + "there" (or `Hi ${who}`) to get a space.
Glossary
- String
- A piece of text: a row of characters in order. Written between "double quotes", 'single quotes' or `backticks`.
- Character
- One letter, digit, space or symbol in a string. Reading one, as in name[0], gives a string of length 1.
- Index
- The position of a character in a string, counting from 0. The last index is length minus 1.
- length
- How many characters (strictly, UTF-16 code units) a string has. "Ada".length is 3.
- Method
- A function that belongs to a value, called with a dot, such as name.toUpperCase().
- Immutable
- Cannot be changed. Strings are immutable: methods and + always make new strings.
- Concatenation
- Joining strings end to end with +. If one side is a string, the other side is turned into text first.
- Template literal
- A string written in backticks. Each ${...} slot is filled with the text of the value inside, and it may span several lines.
Notes and sources
- 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.
- 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.
- 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".
- Double and single quotes make the same kind of string. Backticks also make a string, and only they allow ${...} slots and text that spans several lines.
- name.at(-1) counts from the end and gives "a", the last character; name[-1] gives undefined.
Quiz Unlocks after the last step.