🌱BeginnerModern JavaScript (ES6+)
Template Literals
Backtick strings with embedded expressions, multi-line support, and tagged templates.
Overview
Template literals (introduced in ES6) are string literals delimited by backticks (`) instead of single or double quotes. They have three key capabilities that plain strings lack: embedded expressions via ${...} interpolation, native multi-line support, and tagged templates for advanced processing.
Before template literals, building strings with dynamic values required awkward concatenation: "Hello, " + name + "! You have " + count + " messages." With template literals this becomes: `Hello, ${name}! You have ${count} messages.` which is not just shorter but immediately readable.
The expression inside ${} can be any valid JavaScript: variables, arithmetic, function calls, ternary expressions. Template literals also preserve whitespace and newlines literally, making them ideal for multi-line strings, HTML snippets, and SQL queries in JavaScript.
Key Points
- •Delimited with backticks (`) not single or double quotes
- •${expression} interpolates any JS expression variable, math, function call, ternary
- •Multi-line: newlines inside backtick strings are preserved as-is
- •Nested expressions work: `${arr.map(x => x * 2).join(", ")}`
- •Tagged templates: a function before the backtick processes the template used in styled-components, SQL libraries
- •To include a literal backtick, escape it: \`
Examples
String interpolation replacing concatenation
const name = "Alice";
const score = 95;
// Old way
console.log("Hello, " + name + "! Your score: " + score);
// Template literal
console.log(`Hello, ${name}! Your score: ${score}`);
// Any JS expression works inside the interpolation
const passing = score >= 60;
console.log(`Is passing: ${passing}`);
console.log(`Double: ${score * 2}`);Multi-line strings
const poem = `
Roses are red,
Violets are blue,
JavaScript is great,
And so are you!
`;
console.log(poem);Newlines inside backtick strings are literal newlines no \n needed.
Expressions and function calls inside templates
const items = ["apple", "banana", "cherry"];
const total = 47.5;
console.log(`Items: ${items.join(", ")}`);
// Items: apple, banana, cherry
console.log(`Total: $${total.toFixed(2)}`);
// Total: $47.50
console.log(`Uppercase: ${items[0].toUpperCase()}`);
// Uppercase: APPLECommon Mistakes
- Using regular quotes instead of backticks template literals only work with `...`
- Putting a space between the tag function and the backtick tag`string` not tag `string`
- Forgetting that ${} works inside backtick strings only, not regular strings
Note
Use template literals for any string that contains a variable or spans multiple lines. Keep using regular strings for simple, static values there's no benefit to backticks for `"Hello"` alone.
Exercises
Write JavaScript code to solve each exercise. Run it and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4