JavaScript • Collections and Strings

Template Literals — Build strings with template literals

Combine variables and expressions directly inside strings using backticks for cleaner, more readable JavaScript code.

JavaScript emblem with code brackets, braces, and a code file.
Inside this lesson 10 sections 5 questions 6 figures

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

Brendan Eich creates JavaScript at Netscape. Strings are enclosed in single or double quotes, and concatenation with + is the only way to combine them with variables.

2009 • ES5 Standardized

ECMAScript 5 improves the language in many ways, but string handling remains largely the same. Multiline strings still require awkward workarounds like backslash line continuations.

2011 • TC39 Proposal for Template Literals

The TC39 committee (the group that governs JavaScript standards) begins discussing a template literal syntax using backticks, inspired by similar features in other languages.

2015 • ES6 Releases Template Literals

ECMAScript 2015 officially introduces template literals with backtick syntax, ${} expression placeholders, and native multiline string support.

2020+ • Universal Browser Support

All modern browsers and Node.js versions fully support template literals. They become the preferred way to build strings in professional JavaScript development.

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.

1

Backtick Delimiters

Template literals are wrapped in backtick characters (`...`) instead of regular quotes. This signals to JavaScript that you want to use template literal features.
2

Expression Interpolation

Use ${expression} to embed any JavaScript expression directly inside the string. The expression is evaluated and its result is inserted into the string automatically.
3

Multiline Strings

Template literals preserve line breaks naturally. You can press Enter inside a template literal and the resulting string will contain that newline character — no special escape sequences needed.
4

Tagged Templates

An advanced feature where you place a function name before the backtick. The function receives the string parts and expressions separately, allowing custom processing of the template.
✦

KEY TAKEAWAY

Think of template literals like a fill-in-the-blank worksheet. The backtick string is the worksheet, and each ${} 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.

String Concatenation vs. Template Literals❌ OLD WAY — Concatenationlet name = "Alice";let age = 16;let msg ="Hello, " + name +". You are " + age +" years old.";✅ NEW WAY — Template Literallet name = "Alice";let age = 16;let msg =`Hello, ${name}. You are ${age} years old.`;Both produce the same output:"Hello, Alice. You are 16 years old."Anatomy of a Template Literal`Hello, ${name}. You are ${age} years old.`backtick${} placeholder${} placeholderStatic text sits between placeholders · Expressions inside ${} are evaluated at runtime
The left panel shows the old concatenation method with multiple + 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

‘text1$expr1text2$expr2text3‘→text1+String(expr1)+text2+String(expr2)+text3`text₁ \${expr₁} text₂ \${expr₂} text₃` → text₁ + String(expr₁) + text₂ + String(expr₂) + text₃

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 TypeExampleResult
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!

If you accidentally use regular quotes instead of backticks, the ${} 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.

Template Literal Feature MapFeature 1: Multiline Strings// Old waylet old = "Line 1\nLine 2\nLine 3";// New way`Line 1 Line 2 Line 3`↑ Escape chars needed↑ Natural line breaks!Feature 2: Expression Interpolationlet price = 9.99;let qty = 3;`Total: $${(price * qty).toFixed(2)}`→ "Total: $29.97"Feature 3: Building HTML Dynamicallylet item = "JavaScript Book";let html = `<div class="card"> <h2>${item}</h2></div>`;Produces real HTMLwith the item name insideAll three features use the same backtick syntax — simple and consistent!
This diagram illustrates the three major features of template literals: multiline strings without \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

If your template literal starts getting very long or deeply nested, extract pieces into well-named variables. Readable code is more important than cramming everything into one line. For example, compute values in variables first, then reference those variables in your template.

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. 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. 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. 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. 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 variable report now holds: Report Card ----------- Student: Jordan Subject: Computer Science Score: 87/100 (87.0%) Status: Pass
  5. 5

    Step 5 — Output the Result

    Use console.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.

FeatureConcatenation (+)Template Literals (`)
ReadabilityGets messy with many variables; hard to visualize the final stringReads like natural text with clear placeholders
MultilineRequires \n escape characters or multiple statementsJust press Enter — line breaks are preserved automatically
ExpressionsMust break out of the string, add +, write the expression, then add + againEmbed any expression inline with ${}
Error-prone?Easy to forget a space or quote, causing subtle bugsMuch harder to make spacing mistakes since the string reads naturally
Browser supportWorks everywhere, including very old browsersSupported in all modern browsers (ES6+); may need transpiling for IE11

Comparison of string concatenation and template literals

✦

KEY TAKEAWAY

Concatenation is like building a sentence by cutting out individual words from a magazine and gluing them onto paper — it works, but it's tedious. Template literals are like a fill-in-the-blank form where the sentence is already written out and you just write answers in the blanks. Use template literals as your default for building strings in modern JavaScript.

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.

ConceptTemplate Literal (This Lesson)Tagged Template (Advanced)
Syntax`Hello ${name}`myTag`Hello ${name}`
Who processes it?The JavaScript engine automaticallyA custom function you define
OutputAlways a stringCan return anything (string, object, DOM element)
Use caseEveryday string buildingCustom 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

What character do you use to wrap a template literal in JavaScript, and how does it differ from regular string quotes? Why was this new syntax needed?
Show answer
Template literals use the backtick character (`), 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

Given 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
The correct template literal is: `${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

You have an array 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
The correct template literal is: `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

You're building a weather app. Given 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
The template literal is: `${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

A classmate writes this code and gets unexpected output: 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
The bug is that the classmate used single quotes instead of backticks. With single quotes, JavaScript treats ${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.

Varsity Tutors • JavaScript • Template Literals — Build strings with template literals