SECTION 1
Historical Context & Motivation
Before template literals existed, JavaScript developers had to piece strings together with the + operator in a process called string concatenation. This made code cluttered, hard to read, and prone to mistakes — especially when you needed to insert variables, line breaks, or complex expressions into text. As web applications grew more sophisticated, developers needed a cleaner way to build strings.
Other programming languages like Python and Ruby had already solved this problem with their own string interpolation features. The JavaScript community pushed for a similar solution, and the result was template literals, introduced in ECMAScript 2015 (ES6). This update was one of the biggest improvements to how we work with strings in the language.
1995 • JavaScript Is Born
+ is the only way to combine them with variables.2009 • ES5 Standardized
2011 • TC39 Proposal for Template Literals
2015 • ES6 Releases Template Literals
${} expression placeholders, and native multiline string support.2020+ • Universal Browser Support
The core question template literals answered was simple: How can we embed variables and expressions directly inside a string without ugly concatenation? The backtick-based syntax solved this elegantly, and understanding it is essential for writing modern JavaScript.
SECTION 2
Core Principles & Definitions
Template literals are a modern way to create strings in JavaScript. Instead of wrapping text in single quotes (') or double quotes ("), you use backticks (`). The backtick key is usually located in the upper-left corner of your keyboard, below the Escape key. This small change in syntax unlocks several powerful features.
Backtick Delimiters
`...`) instead of regular quotes. This signals to JavaScript that you want to use template literal features.Expression Interpolation
${expression} to embed any JavaScript expression directly inside the string. The expression is evaluated and its result is inserted into the string automatically.Multiline Strings
Tagged Templates
KEY TAKEAWAY
${} is a blank space where JavaScript automatically writes in the answer for you. Instead of manually gluing pieces of text together with +, you just mark where the blanks go and let the language handle the rest.SECTION 3
Visual Explanation
The following diagram compares the old concatenation approach to the new template literal syntax. Notice how the template literal version reads more like natural English, while the concatenated version is cluttered with quotes and plus signs.
+ operators and quotes. The right panel shows the same result achieved with a single template literal. The bottom section highlights the anatomy: backticks wrap everything, and ${} placeholders mark where expressions are injected.As you can see in the diagram, the template literal version is far easier to read. You can see the entire shape of the output string at a glance, with the placeholders clearly marking where dynamic values will appear. The concatenated version, by contrast, forces your eyes to jump between quotes and plus signs, making it harder to visualize the final result.
SECTION 4
How Template Literals Work Under the Hood
When JavaScript encounters a template literal, it follows a specific process. The engine splits the template into static string segments (the plain text between placeholders) and dynamic expressions (the code inside ${}). Each expression is evaluated, converted to a string using its toString() method, and then the static parts and evaluated expressions are joined together into one final string.
The Interpolation Process
TEMPLATE LITERAL EVALUATION
Where text₁, text₂, text₃ are static string segments and expr₁, expr₂ are JavaScript expressions that get evaluated and converted to strings.
The expression inside ${} can be any valid JavaScript expression. This means you can do much more than just insert variables. You can perform arithmetic, call functions, use ternary operators, or even access object properties — all directly inside the template.
Expressions You Can Use Inside ${}
| Expression Type | Example | Result |
|---|---|---|
| Variable | `Hi ${name}` | "Hi Alice" |
| Arithmetic | `Sum: ${3 + 4}` | "Sum: 7" |
| Function call | `Upper: ${name.toUpperCase()}` | "Upper: ALICE" |
| Ternary operator | `${age >= 18 ? 'adult' : 'minor'}` | "minor" |
| Object property | `Name: ${user.name}` | "Name: Alice" |
Types of JavaScript expressions that work inside template literal placeholders
Watch Out!
${} syntax will NOT work — it will just appear as plain text in your string. Always double-check that you are using backticks (`), not single quotes (').SECTION 5
Key Features in Detail
Multiline Strings
One of the most practical benefits of template literals is multiline string support. With traditional strings, creating a multiline string required adding \n escape characters wherever you wanted a line break. With template literals, you simply press Enter inside the backticks and the line break is preserved in the output. This is especially useful when building HTML markup, formatted messages, or any text that spans multiple lines.
\n escape characters, expression interpolation with ${}, and dynamic HTML building — all using the same backtick syntax.Nesting and Complex Expressions
You can even nest template literals inside other template literals. For example, you might use a ternary expression inside a placeholder that itself contains a template literal. While this is possible, be careful not to make your code too complex. If a template literal becomes hard to read, consider breaking it into separate variables first and then combining them.
Pro Tip
SECTION 6
Worked Example
Let's work through a realistic scenario. Imagine you're building a simple student report card generator. You have a student's information stored in variables, and you need to produce a formatted message.
Building a Report Card Message with Template Literals
- 1
Step 1 — Define the Variables
Start by setting up the student data. We have a name, a subject, a score, and a maximum possible score.let studentName = "Jordan";let subject = "Computer Science";let score = 87;let maxScore = 100; - 2
Step 2 — Compute the Percentage Inside the Template
We can calculate the percentage directly inside a${}placeholder. We use(score / maxScore * 100).toFixed(1)to get one decimal place. - 3
Step 3 — Use a Ternary for a Pass/Fail Label
We can also use a ternary expression to display "Pass" or "Fail" based on whether the score is at least 60.${score >= 60 ? "Pass" : "Fail"} - 4
Step 4 — Assemble the Full Template Literal
Now we put it all together in a single multiline template literal:let report = `Report Card ----------- Student: ${studentName} Subject: ${subject} Score: ${score}/${maxScore} (${(score / maxScore * 100).toFixed(1)}%) Status: ${score >= 60 ? "Pass" : "Fail"}`;The variablereportnow holds:Report Card ----------- Student: Jordan Subject: Computer Science Score: 87/100 (87.0%) Status: Pass - 5
Step 5 — Output the Result
Useconsole.log(report)to display the formatted report card. The output is clean, readable, and required zero concatenation operators.The console displays the fully formatted, multiline report card exactly as written in the template. All expressions (${studentName},${score}, etc.) have been replaced with their evaluated values.
SECTION 7
Template Literals vs. Concatenation
Now that you understand both approaches, let's compare them side by side. While string concatenation still works and you will encounter it in older code, template literals are the preferred modern approach for almost every situation.
| Feature | Concatenation (+) | Template Literals (`) |
|---|---|---|
| Readability | Gets messy with many variables; hard to visualize the final string | Reads like natural text with clear placeholders |
| Multiline | Requires \n escape characters or multiple statements | Just press Enter — line breaks are preserved automatically |
| Expressions | Must break out of the string, add +, write the expression, then add + again | Embed any expression inline with ${} |
| Error-prone? | Easy to forget a space or quote, causing subtle bugs | Much harder to make spacing mistakes since the string reads naturally |
| Browser support | Works everywhere, including very old browsers | Supported in all modern browsers (ES6+); may need transpiling for IE11 |
Comparison of string concatenation and template literals
KEY TAKEAWAY
SECTION 8
Connection to Tagged Templates & Beyond
Template literals have an advanced cousin called tagged templates. A tagged template lets you place a function name right before the backtick. Instead of the engine evaluating the template normally, it passes the string parts and expression values to that function, giving you complete control over how the final string is assembled.
You might encounter tagged templates in libraries like styled-components (for CSS-in-JS) or GraphQL query builders. For now, just know they exist — you'll explore them more as you advance in JavaScript.
| Concept | Template Literal (This Lesson) | Tagged Template (Advanced) |
|---|---|---|
| Syntax | `Hello ${name}` | myTag`Hello ${name}` |
| Who processes it? | The JavaScript engine automatically | A custom function you define |
| Output | Always a string | Can return anything (string, object, DOM element) |
| Use case | Everyday string building | Custom formatting, sanitization, domain-specific languages |
Template literals vs. tagged templates
Another useful built-in tagged template is String.raw, which prevents escape sequences from being processed. For instance, String.raw`Hello\nWorld` returns the literal characters Hello\nWorld instead of creating a line break. This is handy when working with file paths on Windows or regular expressions.
SECTION 9
Practice Problems
Test your understanding of template literals with these five problems. Each one builds on the concepts covered in this lesson, starting with basic recall and progressing to more complex applications.
Question 1: CONCEPTUAL
Show answer
`), found on the upper-left of most keyboards. Regular strings use single quotes (') or double quotes ("). The new syntax was needed because backticks enable two features that regular quotes cannot: expression interpolation via ${} placeholders, and native multiline strings without escape characters. Regular quote strings treat ${} as plain text.Question 2: BASIC CALCULATION
let x = 5; and let y = 12;, write a template literal that produces the string: "5 + 12 = 17". All numbers should come from the variables or expressions, not hardcoded.Show answer
`${x} + ${y} = ${x + y}`. Here, ${x} inserts the value 5, ${y} inserts the value 12, and ${x + y} evaluates the arithmetic expression to insert 17. The static text portions are the " + " and " = " characters between the placeholders.Question 3: INTERMEDIATE
let colors = ["red", "green", "blue"];. Write a template literal that outputs: "There are 3 colors: red, green, blue". Use expressions inside the template to get both the count and the comma-separated list.Show answer
`There are ${colors.length} colors: ${colors.join(", ")}`. The expression ${colors.length} evaluates to 3, and ${colors.join(", ")} calls the array's join() method to produce the comma-separated string "red, green, blue". This demonstrates that you can call methods on objects directly inside placeholders.Question 4: APPLIED
let city = "Chicago";, let tempF = 72;, write a template literal that produces a two-line message: the first line shows the city and temperature in Fahrenheit, and the second line shows the temperature converted to Celsius (formula: (F − 32) × 5/9), rounded to one decimal place.Show answer
`${city}: ${tempF}°F
${city}: ${((tempF - 32) * 5 / 9).toFixed(1)}°C`. The first line uses ${city} and ${tempF} for simple variable insertion. The second line embeds the Celsius conversion formula ((tempF - 32) * 5 / 9) and chains .toFixed(1) to round to one decimal. The result is "Chicago: 72°F" on line one and "Chicago: 22.2°C" on line two. Alternatively, you could use an actual line break inside backticks instead of \n.Question 5: CRITICAL THINKING
let name = "Sam"; let greeting = 'Hello, ${name}!'; The console shows Hello, ${name}! instead of Hello, Sam!. Explain the bug and describe how a tagged template function could be used to add custom behavior (for instance, making all interpolated values uppercase) when fixing this code.Show answer
${name} as literal text rather than a placeholder. The fix is to change to backticks: `Hello, ${name}!`. For the tagged template part, you could write a function like function shout(strings, ...values) { return strings.reduce((result, str, i) => result + str + (values[i] ? values[i].toUpperCase() : ''), ''); } and then call it as shout`Hello, ${name}!` to get "Hello, SAM!". The tag function receives the static string parts as an array and the interpolated values as separate arguments, letting you transform them before combining.SUMMARY
Lesson Summary
Summary
Template literals use backticks instead of quotes and let you embed JavaScript expressions directly in strings using ${} placeholders. This process, called string interpolation, replaces the older approach of string concatenation with the + operator. Introduced in ES6 (2015), template literals produce cleaner, more readable code and are now the standard way to build strings in modern JavaScript.
Beyond simple variable insertion, template literals support multiline strings without escape characters, inline arithmetic and function calls inside placeholders, and an advanced feature called tagged templates for custom string processing. Whenever you need to combine variables with text, reach for backticks first — your future self (and anyone reading your code) will thank you.