Loading lessons...
String Templates
String Templates
Template literals (backticks) make strings much easier to build, especially with variables.
The old way with +
let name = "Ada";
let msg = "Hello, " + name + "!";
The template way
let name = "Ada";
let msg = `Hello, ${name}!`;
Much cleaner, right?
Interpolation
Use ${expression} to insert values directly into the string:
let price = 10;
let tax = 0.2;
let total = `Total: ${price * (1 + tax)}`;
Any JavaScript expression works inside the braces.
Multi-line strings
Template literals can span multiple lines without escape sequences:
let poem = `Roses are red
Violets are blue`;
Why they are better
- No messy plus signs.
- Expressions computed right inside the string.
- Multi-line text is easy.
TL;DR
- Template literals use backticks.
${...}inserts expressions.- They support multi-line strings.
- Much cleaner than string concatenation.