JAVASCRIPT • SYNTAX AND CORE TYPES

Template Literals for Formatting — Use template literals for formatted strings (`${...}`)

Build dynamic, readable strings by embedding expressions directly inside backtick-delimited templates.

Historical Context & Motivation

Before template literals arrived in JavaScript, building strings that included variables was awkward and error-prone. Developers had to glue pieces of text together using the + operator, a process called string concatenation. For example, creating a greeting like "Hello, Alice! You have 5 new messages." required juggling quotation marks, plus signs, and spaces — and a single missing space or quote would break everything.

As web applications grew more complex, developers needed a cleaner way to embed variables and expressions inside strings. Other languages like Python, Ruby, and PHP already offered string interpolation — the ability to drop variables directly into a string without breaking it apart. The JavaScript community pushed for the same convenience, and the solution arrived with the ES2015 (ES6) standard.

1995
JavaScript Is Born
Brendan Eich creates JavaScript in just 10 days at Netscape. Strings use single or double quotes, and concatenation with + is the only way to combine text and variables.
2009
ES5 Standardized
ECMAScript 5 modernizes JavaScript with strict mode and new array methods, but strings remain unchanged. Developers still rely on concatenation for dynamic output.
2011
TC39 Proposals Begin
The TC39 committee (the group that governs JavaScript standards) begins drafting proposals for "quasi-literals," which would later be renamed template literals.
2015
ES2015 (ES6) Released
Template literals officially become part of JavaScript. The backtick character ` and the ${} interpolation syntax give developers a cleaner, more readable way to format strings.
2020+
Universal Adoption
Template literals are supported in all modern browsers and Node.js. They become the standard way to build formatted strings in professional JavaScript codebases.

The central question that template literals answer is straightforward: How can we embed variables and expressions inside a string without breaking it into separate pieces? Understanding this feature will make your code shorter, cleaner, and far easier to read.

Core Principles & Definitions

Template literals rest on a few foundational ideas that distinguish them from traditional strings. Once you grasp these principles, you will see why modern JavaScript developers almost always reach for backticks instead of quotation marks when building dynamic output.

1

Backtick Delimiters

Template literals are wrapped in backticks ( ` ` ) instead of single or double quotes. The backtick key is usually found in the top-left of your keyboard, below the Escape key.
2

Expression Interpolation

The ${expression} syntax lets you insert any JavaScript expression directly into the string. The expression is evaluated, converted to a string, and placed inline.
3

Multi-line Strings

Unlike regular strings, template literals can span multiple lines without needing escape characters like \n. Line breaks in the source code appear as line breaks in the output.
4

Any Valid Expression

Inside ${}, you can use variables, math operations, function calls, ternary operators, and more. If JavaScript can evaluate it, you can interpolate it.
✦ KEY TAKEAWAY
Think of a template literal like a fill-in-the-blank worksheet. The backticks define the worksheet, the regular text is the pre-printed content, and each ${} is a blank space where JavaScript fills in a live answer. Instead of cutting and taping strips of paper together (concatenation), you simply write everything on one sheet and leave blanks for the parts that change.

Visual Explanation

The diagram below compares the old concatenation approach with the template literal approach. Notice how the template literal version keeps the string in one continuous piece, while concatenation breaks it into fragments joined by + operators.

The red section shows classic concatenation with its fragment-and-glue pattern. The green section shows the same output built with a template literal — one clean string with ${} placeholders.

Both approaches produce the exact same output: Hello, Alice! You are 16 years old. However, the template literal version is easier to read, easier to type, and far less likely to introduce bugs caused by missing spaces or mismatched quotation marks. As your strings get longer and include more dynamic values, the advantage of template literals becomes even more dramatic.

How Template Literals Work Under the Hood

When JavaScript encounters a template literal, it performs a well-defined series of steps internally. Understanding this process helps you predict exactly what output you will get, even when your interpolated expressions are complex.

The Evaluation Process

First, the JavaScript engine identifies every ${} placeholder in the template. It then evaluates the expression inside each placeholder from left to right. Each result is converted to a string using JavaScript's built-in ToString rules — numbers become their digit representation, booleans become "true" or "false", and objects call their .toString() method. Finally, the engine concatenates all the static text segments and the stringified values together into one resulting string.

Syntax Patterns

BASIC INTERPOLATION
`static text ${expression} more text`
The expression can be a variable, a math operation, a function call, or any valid JavaScript expression.
MULTI-LINE TEMPLATE
`Line one Line two Line three`
Actual newlines in the source code are preserved in the output. No \n escape characters needed.
EXPRESSION INTERPOLATION
`Total: ${price × quantity}`
Math operations inside ${} are evaluated first, and the result is inserted as text. You can also call functions: ${name.toUpperCase()}.
⚠ Common Mistake
A frequent beginner error is using regular quotes instead of backticks. The syntax "Hello, ${name}" will not interpolate — it will literally print the characters ${name}. You must use backticks ` ` for interpolation to work.

Feature Breakdown & Use Cases

Template literals are more than just a shortcut for concatenation. They unlock several powerful patterns that show up constantly in real-world JavaScript code. The diagram below maps out the key features and how they connect.

The three main branches of template literal functionality: interpolation for embedding expressions, multi-line support for readable text blocks, and tagged templates for advanced processing (covered in later lessons).
Common template literal patterns
FeatureSyntaxWhen to Use
Variable insertion`Hello, ${name}`Whenever you need to embed a value in a string
Math in strings`Total: ${price * qty}`When you need to compute and display a result inline
Function calls`Name: ${getName()}`When a function returns the value you need
Conditional text`${x > 0 ? 'pos' : 'neg'}`When you want different text based on a condition
Multi-line output`Line 1 Line 2`When building HTML snippets, emails, or formatted output

Worked Example: Building a Student Report Card

Let's walk through a realistic scenario. Imagine you are building a small program that generates a formatted report card string for a student. You have the student's name, three test scores, and you need to calculate the average and display everything in a neat, readable format.

Generating a Formatted Report Card
1
Step 1 — Define the VariablesStart by storing the student's information in variables. We have a name and three test scores. const student = "Maria"; const test1 = 88; const test2 = 95; const test3 = 91;
Three scores stored: 88, 95, 91
2
Step 2 — Calculate the AverageWe can compute the average and round it to one decimal place using toFixed(1). const avg = ((test1 + test2 + test3) / 3).toFixed(1);
avg = "91.3"
3
Step 3 — Determine a Letter Grade Using a TernaryWe can use a ternary expression to assign a letter grade. This expression can go directly inside a template literal later, but let's store it for clarity. const grade = avg >= 90 ? "A" : avg >= 80 ? "B" : "C";
grade = "A" (since 91.3 ≥ 90)
4
Step 4 — Build the Report Using a Template LiteralNow we assemble everything into one multi-line template literal. Notice how the backtick string naturally spans multiple lines and embeds each variable. const report = `===== REPORT CARD ===== Student: ${student} Test 1: ${test1} Test 2: ${test2} Test 3: ${test3} Average: ${avg} Grade: ${grade} ========================`;
A complete, formatted report card string with all values embedded
5
Step 5 — View the OutputCalling console.log(report) prints the following: ===== REPORT CARD ===== Student: Maria Test 1: 88 Test 2: 95 Test 3: 91 Average: 91.3 Grade: A ========================
Clean, readable output — no concatenation needed!
💡 Try It Yourself
Open your browser's developer console (press F12, then click the Console tab) and try pasting this code. Change the student name and scores to see how the template literal automatically updates the output.

Template Literals vs. Concatenation

Now that you understand how template literals work, it's important to see exactly where they shine compared to the older concatenation method, and to acknowledge the few situations where you might still use traditional strings.

Side-by-side comparison of string building methods
CriterionConcatenation (+)Template Literals (` `)
ReadabilityFragments separated by + signs; hard to visualize final outputString reads naturally; what you see is close to what you get
Multi-lineRequires \n escape characters or multiple concat linesJust press Enter — newlines are preserved automatically
ExpressionsMust break string, insert expression, re-open stringDrop expression directly in ${} without breaking flow
Error riskEasy to forget spaces, miscount quotes, or misplace +Fewer moving parts = fewer mistakes
Browser supportWorks in all JavaScript versions, including very old browsersWorks in all modern browsers (IE11 not supported, but IE is retired)
Simple static stringsPerfectly fine for strings with no variablesAlso works, but some teams prefer quotes for purely static text
✦ KEY TAKEAWAY
Think of concatenation as building a sentence by cutting words out of a magazine and gluing them onto paper — it works, but it's messy and slow. Template literals are like typing the same sentence in a word processor with blanks that auto-fill — the final product looks exactly as you'd expect, and editing is painless. For any string that includes variables or spans multiple lines, template literals are the modern best practice.

Connection to Advanced Concepts

Template literals are your first step into a broader set of JavaScript string-handling tools. As you advance, you will encounter related features that build on the same backtick syntax and interpolation idea.

From basic template literals to advanced patterns
This LessonAdvanced Concept
Basic interpolation ${variable}Tagged templates — a function placed before the backtick (e.g., html`<p>${text}</p>`) that receives the string parts and values as separate arrays, letting you sanitize, style, or transform the output
Multi-line strings for outputTemplate literal types in TypeScript — TypeScript (a typed superset of JavaScript) uses the same syntax at the type level to create string patterns like type Route = `/api/${string}`
Embedding expressions in stringsJSX in React — React uses a similar curly-brace syntax {expression} inside HTML-like templates. Understanding interpolation prepares you for this pattern.
Calling .toFixed() inside ${}Internationalization (Intl) — the Intl.NumberFormat API lets you format numbers for different locales (currency, decimals) and embed the result in template literals

You do not need to learn these advanced topics right now. The key insight is that mastering basic template literal syntax gives you a foundation that transfers directly to more powerful tools in frameworks like React, libraries like styled-components, and even other languages. Every minute you spend getting comfortable with ${} pays dividends later.

Practice Problems

PROBLEM 1 — CONCEPTUAL
What character must you use to wrap a template literal — single quotes, double quotes, or backticks? Why does it matter which one you choose?
PROBLEM 2 — BASIC CALCULATION
Given const x = 7; and const y = 3;, what does the following expression evaluate to? `${x} + ${y} = ${x + y}`
PROBLEM 3 — INTERMEDIATE
Rewrite the following concatenation using a template literal: const msg = "Dear " + name + ",\nYour order #" + orderId + " ships on " + date + ".";
PROBLEM 4 — APPLIED
You are building a simple web page dynamically. Given these variables: const title = "My Blog"; const posts = 12; const darkMode = true; Write a template literal that produces this HTML string: <h1 class="dark">My Blog</h1><p>12 posts available</p> The class should be "dark" when darkMode is true, and "light" otherwise.
PROBLEM 5 — CRITICAL THINKING
A classmate writes this code and is confused by the output: const price = 19.99; const qty = 3; const receipt = `Total: $${price * qty}`; console.log(receipt); They expected to see Total: $59.97 but got Total: $59.97000000000001. Explain why this happened and suggest a fix using what you've learned about expressions inside ${}.

Lesson Summary

Template literals use backticks instead of quotes and let you embed any JavaScript expression directly in a string using the ${expression} syntax. This process, called string interpolation, replaces the older, error-prone concatenation approach and makes your code dramatically easier to read and maintain. Inside the curly braces, you can place variables, math operations, function calls, and ternary expressions — any valid expression that JavaScript can evaluate.

Template literals also support multi-line strings without escape characters, making them ideal for generating HTML, formatted text, or any output that spans multiple lines. Introduced in ES2015 (ES6), they are now the standard approach in modern JavaScript and serve as a stepping stone to advanced features like tagged templates and JSX in React. When in doubt, reach for backticks — they do everything regular strings do, plus interpolation and multi-line support.

Varsity Tutors • JavaScript • Template Literals for Formatting