Template Literals
String interpolation and multi-line strings with backticks.
2 min read
Template literals, introduced in ES6, use backticks (`) instead of quotes and let you embed expressions directly inside a string, instead of stitching pieces together with +.
String interpolation
const name = "Ada";
const age = 36;
// Before -- string concatenation
console.log("Hi, " + name + ". You are " + age + " years old.");
// With a template literal
console.log(`Hi, ${name}. You are ${age} years old.`);Anything inside ${ } is evaluated as a real JavaScript expression, not just a variable name:
const price = 19.99;
const quantity = 3;
console.log(`Total: $${(price * quantity).toFixed(2)}`); // Total: $59.97Multi-line strings
Regular strings can't span multiple lines without an explicit \n. Template literals can, because they preserve whitespace and line breaks exactly as written:
const message = `Dear ${name},
Thanks for signing up.
We'll be in touch soon.`;Nesting template literals
Expressions inside ${ } can themselves contain template literals, useful for conditional pieces of text:
const itemCount = 3;
console.log(`You have ${itemCount} item${itemCount === 1 ? "" : "s"}.`);
// "You have 3 items."Tagged templates (a brief mention)
A function placed directly before a template literal receives the string pieces and interpolated values separately, letting it process the template before producing a final result:
function shout(strings, ...values) {
return strings.reduce((result, str, i) => `${result}${str}${values[i] ? String(values[i]).toUpperCase() : ""}`, "");
}
shout`Hello, ${name}!`; // "Hello, ADA!"This pattern is what powers libraries like styled-components, though writing your own tagged templates is rare in everyday code — it's worth recognizing the syntax rather than mastering it here.
Template literals are the default way to build strings in modern JavaScript — reach for them over + concatenation any time a string includes a variable. Next, the course covers the array methods (map, filter, reduce) that are just as central to everyday JavaScript.