Values and types
Strings and template literals
Goal: Build and inspect strings · 8 min
Strings can use single quotes, double quotes or backticks. Backticks create template literals that can embed expressions with ${...} and span several lines:
const name = "Ada";
console.log(`Hello, ${name}! 2 + 2 = ${2 + 2}`);
Useful members: .length, .toUpperCase(), .toLowerCase(), .trim(), .includes(x), .slice(start, end), .split(sep), .replaceAll(a, b), .padStart(n, ch). Strings are immutable — methods return new strings.
Worked example: Formatting a time
- padStart(2, "0") adds a leading zero.
- The template literal combines the parts.
- Output:
09:05
const h = 9, m = 5;
console.log(`${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`);Output:
09:05