Historical Context & Motivation
Before template literals existed in JavaScript, building strings that contained variable data was awkward and error-prone. Developers had to rely on string concatenation — gluing pieces together with the + operator. Even a simple greeting like "Hello, " + name + "! You are " + age + " years old." was cluttered with quotation marks and plus signs, making the code hard to read and easy to break with a missing space or quote.
Other programming languages — Python, Ruby, PHP, and C# — had long offered cleaner ways to embed variables inside strings. JavaScript developers wanted the same convenience. The arrival of ES6 (ECMAScript 2015) finally brought template literals to the language, solving a pain point that had frustrated programmers for nearly two decades.
+ is the sole way to combine them with data.${}, and multi-line strings. All major browsers adopt the feature within two years.The central question template literals answer is simple: How can we embed live data inside a string without losing readability? The rest of this lesson explores exactly how they work and why they make your code cleaner.
Core Principles & Definitions
Template literals revolve around a small set of ideas. Once you understand these principles, you can use them confidently in any JavaScript project.
Backtick Delimiters
` ) instead of single or double quotes. The backtick is typically located to the left of the 1 key on a US keyboard.Embedded Expressions
${...} within a template literal. The expression is evaluated at runtime and its result is inserted into the string.Multi-line Strings
Automatic Type Coercion
${} placeholder, JavaScript automatically converts it to a string — no manual conversion needed.${} is a blank space where JavaScript fills in a live answer. Instead of taping separate word cards together (concatenation), you write one continuous sentence with blanks that get filled automatically.Visual Explanation — Anatomy of a Template Literal
The diagram below breaks down a single template literal into its component parts. Pay attention to how the backticks wrap the entire string, how static text sits alongside embedded expressions, and how the final output string is produced.
Notice that the JavaScript engine replaces each ${} placeholder with the current value of its expression at the moment the line runs. The variable name is looked up, the math score * 10 is calculated, and both results are seamlessly woven into the surrounding text. No plus signs, no extra quotes — just one clean, readable string.
How Template Literals Work Under the Hood
When the JavaScript engine encounters a template literal, it follows a predictable process. Understanding this mechanism helps you predict what any template literal will produce, even when the expressions inside are complex.
The Evaluation Process
First, the engine identifies every ${} placeholder in the template. It splits the template into an alternating list of static parts (the plain text between placeholders) and dynamic parts (the expression results). Each expression is evaluated left to right, converted to a string if necessary, and then the static and dynamic parts are stitched together in order to produce one final string value.
Syntax Pattern
${} can hold any valid expression: a variable, a math operation, a function call, or even another template literal.What Counts as an Expression?
- Variable reference —
${userName} - Arithmetic —
${price * 1.08}(price with 8% tax) - Function call —
${name.toUpperCase()} - Ternary operator —
${age >= 18 ? "adult" : "minor"} - Nested template literal —
${`Item: ${itemName}`}
if or for) are not expressions and cannot go inside ${}. Use the ternary operator ? : instead of if/else when you need conditional logic inside a template literal.Concatenation vs. Template Literals — Side by Side
The best way to appreciate template literals is to see the same output produced by both old-style concatenation and the new syntax. The diagram below places them side by side so you can compare readability, character count, and where mistakes tend to creep in.
| Feature | Concatenation | Template Literal |
|---|---|---|
| Delimiter | "..." or '...' | `...` |
| Embed a variable | "Hi " + name | `Hi ${name}` |
| Multi-line | Requires \n escape | Just press Enter inside the backticks |
| Expressions | Break out of string, compute, re-enter string | Write the expression directly inside ${} |
| Readability | Decreases as complexity grows | Stays high — code mirrors the output |
Worked Example — Building a Student Report Card
Let's walk through a realistic example. Imagine you're writing a program that prints a short report card message for a student. You know the student's name, their numeric score, and you need to calculate their letter grade and display it all in a neatly formatted string.
let studentName = "Priya";
let score = 87;studentName = "Priya", score = 87let letter = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";letter = "B"let report = `Report Card
-----------
Student: ${studentName}
Score: ${score}/100
Grade: ${letter}
Points to A: ${90 - score}`;studentName, score), one variable (letter), and one arithmetic expression (90 - score).console.log(report);
The console displays:
Report Card
-----------
Student: Priya
Score: 87/100
Grade: B
Points to A: 3studentName and score to your own values and watch the output update.Strengths, Limitations & Best Practices
Template literals are a powerful upgrade to JavaScript's string toolkit, but they are not a silver bullet. The table below summarizes where they shine and where you should be cautious.
| Strengths ✅ | Limitations ⚠️ |
|---|---|
| Dramatically improves readability for dynamic strings | Cannot use statements (if, for, while) inside ${} — only expressions |
Multi-line strings without \n escapes | Extra whitespace and indentation inside backticks become part of the string — can cause unexpected formatting |
| Supports any valid expression, including function calls | Very complex expressions inside ${} can hurt readability — extract into a variable first |
| Automatic type coercion converts numbers and booleans to strings | Not supported in Internet Explorer (though IE is effectively retired) |
${} short and simple. If an expression takes more than about 20 characters, store its result in a descriptive variable first and embed the variable instead. Think of it like writing a sentence: you wouldn't insert a whole paragraph into the middle of another sentence.Connection to Advanced Concepts — Tagged Templates
The template literals you have learned so far are sometimes called untagged template literals. JavaScript also supports tagged template literals, which let you place a function name right before the opening backtick. The function receives the static parts and the expression values as separate arguments, giving you full control over how the final string is assembled.
| Feature | Untagged (This Lesson) | Tagged (Advanced) |
|---|---|---|
| Syntax | `Hello ${name}` | myTag`Hello ${name}` |
| Who builds the final string? | The JavaScript engine, automatically | Your custom myTag function |
| Use cases | General-purpose string formatting | HTML sanitization, internationalization, CSS-in-JS (e.g., styled-components) |
| When to learn | Now — foundational skill | After mastering functions and arrays |
You don't need to master tagged templates right now, but knowing they exist gives you a preview of where this syntax leads. Many popular libraries — including React's styled-components — are built on tagged templates. The untagged template literals you are learning today are the essential foundation that makes those advanced tools possible.
Practice Problems
Test your understanding with these five problems. They start with a simple concept check and build toward more complex scenarios. Try writing your answers in a code editor or the browser console before reading the solutions.
let item = "Notebook"; let price = 3.50; let qty = 4;, write a single template literal that produces the output: 4 Notebooks cost $14.00. Hint: use .toFixed(2) to format the price."Welcome, " + user + "!\nYou have " + msgs + " unread message" + (msgs !== 1 ? "s" : "") + "."
Make sure your version handles the plural "s" correctly using a ternary expression inside ${}.let city = "Seattle"; let tempF = 58; let condition = "cloudy";. Write a template literal that produces a multi-line forecast card. Include the temperature in both Fahrenheit and Celsius (use the formula C = (F − 32) × 5 ÷ 9, rounded to one decimal place). The expected output should look like:
🌤 Weather for Seattle
Condition: Cloudy
Temp: 58°F / 14.4°Clet x = 5;
let y = 10;
console.log(`Sum: ${x + y}`);
console.log(`Expression: ${x} + ${y}`);
The first line prints Sum: 15 and the second prints Expression: 5 + 10. Explain why the outputs differ even though both lines contain x, +, and y. What general rule does this illustrate about what goes inside vs. outside of ${}?Lesson Summary
Template literals are JavaScript strings delimited by backticks instead of single or double quotes. They were introduced in ES6 (2015) to solve the readability problems of string concatenation. By using ${} placeholders, you can embed any valid JavaScript expression — variables, arithmetic, function calls, or ternary operators — directly inside the string. The JavaScript engine evaluates each expression at runtime and stitches the results into one final string.
Template literals also support multi-line strings without escape characters, and they perform automatic type coercion so numbers and booleans are converted to strings seamlessly. Keep expressions inside ${} short and readable. As you advance, you will encounter tagged template literals — a powerful extension used in frameworks like React. For now, mastering the backtick-and-placeholder pattern gives you a cleaner, more professional way to build every dynamic string in your programs.