Historical Context & Motivation
Before template literals arrived in JavaScript, building strings that included variables was awkward and error-prone. Developers had to glue pieces of text together using the + operator, a process called string concatenation. For example, creating a greeting like "Hello, Alice! You have 5 new messages." required juggling quotation marks, plus signs, and spaces — and a single missing space or quote would break everything.
As web applications grew more complex, developers needed a cleaner way to embed variables and expressions inside strings. Other languages like Python, Ruby, and PHP already offered string interpolation — the ability to drop variables directly into a string without breaking it apart. The JavaScript community pushed for the same convenience, and the solution arrived with the ES2015 (ES6) standard.
+ is the only way to combine text and variables.` and the ${} interpolation syntax give developers a cleaner, more readable way to format strings.The central question that template literals answer is straightforward: How can we embed variables and expressions inside a string without breaking it into separate pieces? Understanding this feature will make your code shorter, cleaner, and far easier to read.
Core Principles & Definitions
Template literals rest on a few foundational ideas that distinguish them from traditional strings. Once you grasp these principles, you will see why modern JavaScript developers almost always reach for backticks instead of quotation marks when building dynamic output.
Backtick Delimiters
` ` ) instead of single or double quotes. The backtick key is usually found in the top-left of your keyboard, below the Escape key.Expression Interpolation
${expression} syntax lets you insert any JavaScript expression directly into the string. The expression is evaluated, converted to a string, and placed inline.Multi-line Strings
\n. Line breaks in the source code appear as line breaks in the output.Any Valid Expression
${}, you can use variables, math operations, function calls, ternary operators, and more. If JavaScript can evaluate it, you can interpolate it.${} is a blank space where JavaScript fills in a live answer. Instead of cutting and taping strips of paper together (concatenation), you simply write everything on one sheet and leave blanks for the parts that change.Visual Explanation
The diagram below compares the old concatenation approach with the template literal approach. Notice how the template literal version keeps the string in one continuous piece, while concatenation breaks it into fragments joined by + operators.
${} placeholders.Both approaches produce the exact same output: Hello, Alice! You are 16 years old. However, the template literal version is easier to read, easier to type, and far less likely to introduce bugs caused by missing spaces or mismatched quotation marks. As your strings get longer and include more dynamic values, the advantage of template literals becomes even more dramatic.
How Template Literals Work Under the Hood
When JavaScript encounters a template literal, it performs a well-defined series of steps internally. Understanding this process helps you predict exactly what output you will get, even when your interpolated expressions are complex.
The Evaluation Process
First, the JavaScript engine identifies every ${} placeholder in the template. It then evaluates the expression inside each placeholder from left to right. Each result is converted to a string using JavaScript's built-in ToString rules — numbers become their digit representation, booleans become "true" or "false", and objects call their .toString() method. Finally, the engine concatenates all the static text segments and the stringified values together into one resulting string.
Syntax Patterns
expression can be a variable, a math operation, a function call, or any valid JavaScript expression.\n escape characters needed.${} are evaluated first, and the result is inserted as text. You can also call functions: ${name.toUpperCase()}."Hello, ${name}" will not interpolate — it will literally print the characters ${name}. You must use backticks ` ` for interpolation to work.Feature Breakdown & Use Cases
Template literals are more than just a shortcut for concatenation. They unlock several powerful patterns that show up constantly in real-world JavaScript code. The diagram below maps out the key features and how they connect.
| Feature | Syntax | When to Use |
|---|---|---|
| Variable insertion | `Hello, ${name}` | Whenever you need to embed a value in a string |
| Math in strings | `Total: ${price * qty}` | When you need to compute and display a result inline |
| Function calls | `Name: ${getName()}` | When a function returns the value you need |
| Conditional text | `${x > 0 ? 'pos' : 'neg'}` | When you want different text based on a condition |
| Multi-line output | `Line 1
Line 2` | When building HTML snippets, emails, or formatted output |
Worked Example: Building a Student Report Card
Let's walk through a realistic scenario. Imagine you are building a small program that generates a formatted report card string for a student. You have the student's name, three test scores, and you need to calculate the average and display everything in a neat, readable format.
const student = "Maria";
const test1 = 88;
const test2 = 95;
const test3 = 91;toFixed(1).
const avg = ((test1 + test2 + test3) / 3).toFixed(1);"91.3"const grade = avg >= 90 ? "A" : avg >= 80 ? "B" : "C";"A" (since 91.3 ≥ 90)const report = `===== REPORT CARD =====
Student: ${student}
Test 1: ${test1}
Test 2: ${test2}
Test 3: ${test3}
Average: ${avg}
Grade: ${grade}
========================`;console.log(report) prints the following:
===== REPORT CARD =====
Student: Maria
Test 1: 88
Test 2: 95
Test 3: 91
Average: 91.3
Grade: A
========================Template Literals vs. Concatenation
Now that you understand how template literals work, it's important to see exactly where they shine compared to the older concatenation method, and to acknowledge the few situations where you might still use traditional strings.
| Criterion | Concatenation (+) | Template Literals (` `) |
|---|---|---|
| Readability | Fragments separated by + signs; hard to visualize final output | String reads naturally; what you see is close to what you get |
| Multi-line | Requires \n escape characters or multiple concat lines | Just press Enter — newlines are preserved automatically |
| Expressions | Must break string, insert expression, re-open string | Drop expression directly in ${} without breaking flow |
| Error risk | Easy to forget spaces, miscount quotes, or misplace + | Fewer moving parts = fewer mistakes |
| Browser support | Works in all JavaScript versions, including very old browsers | Works in all modern browsers (IE11 not supported, but IE is retired) |
| Simple static strings | Perfectly fine for strings with no variables | Also works, but some teams prefer quotes for purely static text |
Connection to Advanced Concepts
Template literals are your first step into a broader set of JavaScript string-handling tools. As you advance, you will encounter related features that build on the same backtick syntax and interpolation idea.
| This Lesson | Advanced Concept |
|---|---|
Basic interpolation ${variable} | Tagged templates — a function placed before the backtick (e.g., html`<p>${text}</p>`) that receives the string parts and values as separate arrays, letting you sanitize, style, or transform the output |
| Multi-line strings for output | Template literal types in TypeScript — TypeScript (a typed superset of JavaScript) uses the same syntax at the type level to create string patterns like type Route = `/api/${string}` |
| Embedding expressions in strings | JSX in React — React uses a similar curly-brace syntax {expression} inside HTML-like templates. Understanding interpolation prepares you for this pattern. |
Calling .toFixed() inside ${} | Internationalization (Intl) — the Intl.NumberFormat API lets you format numbers for different locales (currency, decimals) and embed the result in template literals |
You do not need to learn these advanced topics right now. The key insight is that mastering basic template literal syntax gives you a foundation that transfers directly to more powerful tools in frameworks like React, libraries like styled-components, and even other languages. Every minute you spend getting comfortable with ${} pays dividends later.
Practice Problems
const x = 7; and const y = 3;, what does the following expression evaluate to?
`${x} + ${y} = ${x + y}`const msg = "Dear " + name + ",\nYour order #" + orderId + " ships on " + date + ".";const title = "My Blog";
const posts = 12;
const darkMode = true;
Write a template literal that produces this HTML string:
<h1 class="dark">My Blog</h1><p>12 posts available</p>
The class should be "dark" when darkMode is true, and "light" otherwise.const price = 19.99;
const qty = 3;
const receipt = `Total: $${price * qty}`;
console.log(receipt);
They expected to see Total: $59.97 but got Total: $59.97000000000001. Explain why this happened and suggest a fix using what you've learned about expressions inside ${}.Lesson Summary
Template literals use backticks instead of quotes and let you embed any JavaScript expression directly in a string using the ${expression} syntax. This process, called string interpolation, replaces the older, error-prone concatenation approach and makes your code dramatically easier to read and maintain. Inside the curly braces, you can place variables, math operations, function calls, and ternary expressions — any valid expression that JavaScript can evaluate.
Template literals also support multi-line strings without escape characters, making them ideal for generating HTML, formatted text, or any output that spans multiple lines. Introduced in ES2015 (ES6), they are now the standard approach in modern JavaScript and serve as a stepping stone to advanced features like tagged templates and JSX in React. When in doubt, reach for backticks — they do everything regular strings do, plus interpolation and multi-line support.