JavaScript From Zero · 16 min · 120 XP
Strings and template literals
Build text with template literals, clean up what people type, and remember that string methods hand back a new string.
Text in JavaScript is a string, written in single or double quotes: "Headlamp" or 'Headlamp'. Joining strings with + works, but gets hard to read the moment a sentence has more than one value in it: "Total: $" + total + " for " + count + " items".
A template literal uses backticks (`, usually the key left of 1) instead of quotes. Inside it, ${ } drops in the value of any expression: a variable, a calculation, a function call, even a ternary. It can also run over several lines. From here on, this is how you build text.
const name = "Ada";
const count = 3;
const total = 42.5;
`Hello, ${name}!` // "Hello, Ada!"
`Total: $${total.toFixed(2)}` // "Total: $42.50"
`${count} ${count === 1 ? "item" : "items"}` // "3 items"
'Hello, ${name}' // "Hello, ${name}", exactly as typed: quotes don't interpolateTwo traps. Only backticks interpolate: with ordinary quotes, ${name} is printed as those seven characters. And ${} turns anything into text, so a missing value doesn't fail, it shows up on the page as undefined, null or [object Object]. When text looks wrong, check the value going in before the template around it.
Cleaning up what people type. trim() removes spaces from both ends, and toLowerCase() makes comparisons ignore case, so " Ada@Example.com " and "ada@example.com" can be treated as the same address. includes("lamp"), startsWith("SKU-") and endsWith(".pdf") answer yes/no questions. slice(-4) takes the last four characters, padStart(3, "0") turns "7" into "007", and replaceAll(" ", "") strips every space. (split turns a string into an array; you'll use it once arrays arrive in the next module.)
Strings never change. Every string method returns a new string and leaves the original alone. email.trim(); on its own line does nothing useful; keep the result: const clean = email.trim();. That's the same rule as the array methods that don't mutate, which you'll meet next module.
Template literals build text. Later in this course you'll put text on the page, and building HTML with a template literal and handing it to innerHTML is how cross-site scripting happens. The DOM lessons show the safe way.
Loading your workspace…