SECTION 1
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.
1995 • JavaScript Is Born
+ is the sole way to combine them with data.2009 • ES5 Standardized
2011 • TC39 Proposals Begin
2015 • ES6 / ECMAScript 2015
${}, and multi-line strings. All major browsers adopt the feature within two years.2020+ • Universal Adoption
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.
SECTION 2
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.KEY TAKEAWAY
${} 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.SECTION 3
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.
SECTION 4
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
TEMPLATE LITERAL SYNTAX
Every template literal starts and ends with a backtick. Each ${} 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}`}
Common Pitfall
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.SECTION 5
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 |
Key differences between concatenation and template literals
SECTION 6
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.
Building a Report Card Message
- 1
Step 1 — Declare the Variables
Start by storing the student's data in variables. We have the student's name and their numerical score.let studentName = "Priya";let score = 87;Two variables ready:studentName= "Priya",score= 87 - 2
Step 2 — Determine the Letter Grade
Use a ternary expression to assign a letter grade. We will embed this logic directly inside the template literal later, but let's first see it as a standalone variable.let letter = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F";Since 87 ≥ 80 but < 90,letter= "B" - 3
Step 3 — Build the Template Literal
Now construct a multi-line template literal embedding both variables and an expression that calculates how many points until an A.let report = `Report Card ----------- Student: ${studentName} Score: ${score}/100 Grade: ${letter} Points to A: ${90 - score}`;The template literal contains two variable references (studentName,score), one variable (letter), and one arithmetic expression (90 - score). - 4
Step 4 — Log the Output
console.log(report);The console displays:Report Card ----------- Student: Priya Score: 87/100 Grade: B Points to A: 3A clean, readable, multi-line report — built with zero concatenation operators.
Try It Yourself
studentName and score to your own values and watch the output update.SECTION 7
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) |
Strengths vs. limitations of template literals
BEST PRACTICE
${} 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.SECTION 8
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 |
Untagged vs. tagged template literals
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.
SECTION 9
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.
Question 1: CONCEPTUAL
Show answer
` ), and an embedded expression begins with ${ and ends with }. Unlike concatenation, which requires you to break out of the string with a closing quote, add a + operator, insert the expression, add another +, and reopen the string with a new quote, template literals let you keep the entire string in one continuous block. This makes the code more readable and less error-prone.Question 2: BASIC CALCULATION
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.Show answer
`${qty} ${item}s cost $${(price * qty).toFixed(2)}`. Inside the first ${}, the variable qty evaluates to 4. The second inserts the item name. The third evaluates price * qty (3.50 × 4 = 14) and then calls .toFixed(2) to ensure two decimal places, producing "14.00". The dollar sign before ${ is treated as literal text because it is not immediately followed by { — wait, actually it is adjacent. To include a literal dollar sign, just place it before the expression: the $ before ${(price * qty)} is part of the static text since $${ starts the expression at the second dollar sign.Question 3: INTERMEDIATE
"Welcome, " + user + "!\nYou have " + msgs + " unread message" + (msgs !== 1 ? "s" : "") + "."
Make sure your version handles the plural "s" correctly using a ternary expression inside ${}.Show answer
`Welcome, ${user}!
You have ${msgs} unread message${msgs !== 1 ? "s" : ""}. `. The newline is created by simply pressing Enter inside the backticks instead of writing \n. The ternary msgs !== 1 ? "s" : "" inside the last ${} adds an "s" when the count is anything other than 1, correctly producing "messages" for 0, 2, 3, etc., and "message" for exactly 1. This approach is far easier to read than the original concatenation.Question 4: APPLIED
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°CShow answer
`🌤 Weather for ${city}
Condition: ${condition[0].toUpperCase() + condition.slice(1)}
Temp: ${tempF}°F / ${((tempF - 32) * 5 / 9).toFixed(1)}°C`
The Celsius conversion expression ((tempF - 32) * 5 / 9).toFixed(1) calculates (58 − 32) × 5 ÷ 9 = 14.444…, then .toFixed(1) rounds it to 14.4. The condition is capitalized using condition[0].toUpperCase() + condition.slice(1). Multi-line formatting comes naturally from pressing Enter inside the backticks. This showcases how template literals can embed both math and method calls.Question 5: CRITICAL THINKING
let 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 ${}?Show answer
console.log, the expression x + y lives entirely inside one ${} block, so JavaScript evaluates it as arithmetic: 5 + 10 = 15. In the second line, x and y are in separate ${} blocks, and the + between them is static text — just a literal plus sign character that is part of the string, not an operator. The general rule: anything inside ${} is executed as JavaScript code, while anything outside is treated as plain text. This distinction is crucial — the placement of the curly braces determines whether a symbol is an operator or just a character in the string.SUMMARY
Lesson Summary
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.