Sub topic 1
Creating Strings: Quotes, Escapes, and Primitives
Prerequisites
This chapter assumes you know basic JavaScript syntax (variables, functions, control flow) and can run code in a browser console or Node.js.
Quotes and Escape Sequences
A string is a primitive value that holds a sequence of text. You can write one with single quotes or double quotes, and the two forms behave the same. An escape sequence starts with a backslash and stands for a character that is hard to type directly.
const a = 'single';
const b = "double";
const quote = 'It\'s fine'; // escaped quote
const lines = "one\ntwo"; // \n is a newline
const tab = "col1\tcol2"; // \t is a tab
const path = "C:\\temp"; // \\ is one backslash
const smile = "\u{1F600}"; // Unicode code point escape
console.log(quote, path); // It's fine C:\tempWhy Strings Never Change
Strings are immutable: once a string exists, its characters can't be changed. Methods such as toUpperCase build and return a new string. If you assign to an index, as in s[0] = "J", nothing happens in sloppy mode. In strict mode, the same assignment throws a TypeError.
Length and Accessing Characters
length gives the number of characters (more precisely, UTF-16 code units). Indexes start at 0. Bracket notation returns undefined when the index is out of range, and charAt returns an empty string. The at method accepts negative indexes, which count back from the end.
const s = "hello";
console.log(s.length); // 5
console.log(s[0], s.at(-1)); // h o
console.log(s.charAt(10)); // "" (empty string)
console.log(s[10]); // undefined
const upper = s.toUpperCase();
console.log(s, upper); // hello HELLOTemplate Literals and Interpolation
A template literal is a string written with backticks. You can put any expression inside ${}, and line breaks inside the backticks stay in the string.
const user = { name: "Ada", items: 3 };
const msg = `${user.name} has ${user.items} item${user.items === 1 ? "" : "s"}`;
console.log(msg); // Ada has 3 items
const card = `Name: ${user.name}
Items: ${user.items * 2}`;
console.log(card);| Form | Interpolation | Multi-line without escapes |
|---|---|---|
| `'...'` | No | No |
| `"..."` | No | No |
| `` `...` `` | Yes | Yes |
Exercise
What does this print, and why? const w = "code"; w.toUpperCase(); console.log(w, w[-1], w.at(-1));
Show answer
It prints "code undefined e". toUpperCase returns a new string that is thrown away, so w stays the same. w[-1] looks up a property named "-1", which doesn't exist, so it gives undefined. at(-1) counts back from the end and returns "e".
Exercise
Rewrite "Total: " + price + " USD" as a template literal.
Show answer
Total: ${price} USD