Guide to JavaScript Template Literals Strings
Template literals are the modern way to build strings in JavaScript. Learn backtick syntax, expression interpolation, multi-line strings, and when to use them over regular quotes.
JavaScript template literals are strings created with backticks instead of single or double quotes. A template literal lets you embed variables and expressions directly into the string using ${}, and it can span multiple lines without any special characters.
Template literals were introduced in ES6 and are now the standard way to build dynamic strings. They solve two long-standing frustrations: messy concatenation with the plus operator and the lack of clean multi-line strings.
Here is the simplest example:
const name = "Maya";
const greeting = `Hello, ${name}!`;
console.log(greeting);Running this code prints Hello, Maya! to the console.
The ${name} part is called a placeholder. JavaScript evaluates the expression between the curly braces, converts the result to a string, and inserts it at that position.
No plus operator, no manual spacing, no closing and reopening quotes.
Template literal syntax
The only syntax rule is that a template literal must be wrapped in backticks. That is the key above the Tab key on most keyboards, shared with the tilde character.
Compare the two approaches for the same output:
const item = "book";
const price = 12;
// Concatenation with quotes and +
const quoted = 'The ' + item + ' costs $' + price + '.';
// Template literal
const template = `The ${item} costs $${price}.`;
console.log(quoted);
console.log(template);Both produce The book costs $12. But the template literal version keeps the sentence intact. You can read the full text without mentally parsing operators and quote boundaries.
String interpolation with ${}
The ${} syntax is called interpolation. Anything inside the curly braces is treated as a JavaScript expression, evaluated, and converted to a string.
const a = 5;
const b = 3;
console.log(`${a} + ${b} = ${a + b}`);
console.log(`Uppercase: ${"hello".toUpperCase()}`);
console.log(`Is adult: ${17 >= 18}`);The first line computes the sum inside the placeholder and prints the full sentence. The second prints Uppercase: HELLO because .toUpperCase() runs on the string before interpolation. The third prints Is adult: false because the comparison result gets converted to text.
Multi-line strings
Before template literals, multi-line strings required escape sequences or concatenation. Template literals let you type line breaks directly, and they become part of the string.
const address = `Rune Hub
123 Developer Lane
San Francisco, CA 94107`;
console.log(address);The console shows three lines exactly as typed. Every Enter you press inside the backticks becomes a newline character in the output. For a deeper dive into multi-line patterns and real-world use cases like HTML templates, see the guide on creating multi-line strings with backticks.
Expressions inside ${}
Because ${} accepts any expression, you can embed math, method calls, and ternary operators without writing extra variables.
const cart = { items: 4, total: 59.97 };
const message = `You have ${cart.items} item${cart.items !== 1 ? "s" : ""}
in your cart. Total: $${cart.total.toFixed(2)}`;
console.log(message);The ternary operator inside ${} handles singular versus plural: when cart.items is 1, it appends an empty string instead of "s". The .toFixed(2) call ensures two decimal places on the total. Both expressions run inline without temporary variables.
Nesting template literals inside array methods like .map() is another common pattern when formatting lists:
const user = { name: "Alex", scores: [85, 92, 78] };
const report = `${user.name}'s scores: ${user.scores
.map((s, i) => `Test ${i + 1}: ${s}`)
.join(", ")}`;
console.log(report);This prints Alex's scores: Test 1: 85, Test 2: 92, Test 3: 78. The inner template literal inside .map() formats each individual score, and .join(", ") stitches them together into a comma-separated list.
Tagged templates
A tagged template is a function that receives the raw string parts and interpolated values separately, then returns a custom result. Libraries like styled-components use this pattern for CSS-in-JS.
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i] ? `<strong>${values[i]}</strong>` : "";
return result + str + value;
}, "");
}
const lang = "Python";
console.log(highlight`Learning ${lang} at advanced level`);The highlight function receives the static text parts as an array and each ${} value as a separate argument. It wraps each interpolated value in strong tags before reassembling the string. The output is Learning <strong>Python</strong> at advanced level.
As a beginner you will rarely write your own tag function, but understanding the pattern helps when you encounter libraries that use it.
Common mistakes
Forgetting backticks and using regular quotes. This is the most frequent error for beginners:
const name = "Sam";
const wrong = 'Hello, ${name}!';
console.log(wrong);This prints the literal text Hello, ${name}! instead of a greeting with the name filled in. Only backticks trigger interpolation.
Single and double quotes treat ${} as regular characters, not as an interpolation signal.
Confusing template literals with JSON. JSON requires double quotes around keys and string values, and template literals are a JavaScript feature only.
Do not use backticks in a .json file. JSON always requires plain double-quoted syntax, even when the data came from a template literal in your JavaScript code.
Embedding too much logic in a single placeholder. If an expression spans more than one short line, extract it into a variable or function first. Template literals are meant to make reading easier, not to pack complex logic into strings.
Escaping special characters
To include a literal backtick inside a template literal, escape it with a backslash. To include ${ as literal text, escape the dollar sign.
console.log(`Use \`backticks\` for template literals.`);
console.log(`The syntax is \${expression}.`);The first line prints the sentence with literal backticks included. The second prints The syntax is ${expression}. with the dollar-brace appearing as literal text instead of triggering interpolation.
For a broader overview of all string manipulation tools, see the JavaScript string methods guide.
Rune AI
Key Insights
- Template literals use backticks instead of single or double quotes.
- Use ${expression} to embed variables and expressions directly into a string.
- Template literals can span multiple lines without escape characters.
- You can put any valid JavaScript expression inside ${}, including function calls, math, and conditionals.
- Prefer template literals over + concatenation for readability.
Frequently Asked Questions
What is the difference between template literals and regular strings?
Can I nest template literals inside each other?
Do template literals work in all browsers?
Conclusion
Template literals are the modern, readable way to build strings in JavaScript. Use them whenever you need to insert variables into text, write multi-line strings, or embed expressions. They replace most use cases for string concatenation with the + operator.
More in this topic
Is JavaScript Frontend or Backend? Full Guide
JavaScript is both a frontend and backend language. Learn the difference between browser JavaScript and Node.js, what each is used for, and which one you should learn first.
Learn JavaScript Step by Step Tutorial with Real Examples
Follow a hands-on tutorial that teaches JavaScript by building a real interactive page. Write your first variables, functions, and event listeners with examples you can run.
JavaScript Tutorial: Complete Beginner's Guide to Programming in 2025
A structured learning path for absolute beginners. Learn what to study first, how to practice, and which JavaScript concepts matter most when you are starting from zero.