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.
+ is the only way to combine them with variables.${} expression placeholders, and native multiline string 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.
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
${} 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.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.
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
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" |
${} 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 (').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.
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.
let studentName = "Jordan";
let subject = "Computer Science";
let score = 87;
let maxScore = 100;${} placeholder. We use (score / maxScore * 100).toFixed(1) to get one decimal place.${score >= 60 ? "Pass" : "Fail"}let report = `Report Card
-----------
Student: ${studentName}
Subject: ${subject}
Score: ${score}/${maxScore} (${(score / maxScore * 100).toFixed(1)}%)
Status: ${score >= 60 ? "Pass" : "Fail"}`;report now holds:
Report Card
-----------
Student: Jordan
Subject: Computer Science
Score: 87/100 (87.0%)
Status: Passconsole.log(report) to display the formatted report card. The output is clean, readable, and required zero concatenation operators.${studentName}, ${score}, etc.) have been replaced with their evaluated values.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 |
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 |
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.
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.
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.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.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.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.Lesson 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.