COMPUTER PROGRAMMING 1 (JAVASCRIPT) • ENVIRONMENT, SYNTAX & TYPES

Template Literals — I can use template literals to format readable output with embedded expressions.

Build dynamic, readable strings by embedding variables and expressions directly inside backtick-delimited text.

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
Brendan Eich creates JavaScript in ten days at Netscape. Strings can only be created with single or double quotes, and concatenation with + is the sole way to combine them with data.
2009
ES5 Standardized
ECMAScript 5 adds strict mode and JSON support, but string handling remains unchanged. Developers still rely on concatenation for dynamic output.
2011
TC39 Proposals Begin
The TC39 committee (the group that evolves JavaScript) begins discussing "quasi-literals," an early name for what would become template literals.
2015
ES6 / ECMAScript 2015
Template literals ship as part of ES6, introducing backtick syntax, embedded expressions via ${}, and multi-line strings. All major browsers adopt the feature within two years.
2020+
Universal Adoption
Template literals are now the standard way to build dynamic strings in modern JavaScript, React, Node.js, and countless frameworks.

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.

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.

1

Backtick Delimiters

Template literals use the backtick character ( ` ) instead of single or double quotes. The backtick is typically located to the left of the 1 key on a US keyboard.
2

Embedded Expressions

Any valid JavaScript expression can be placed inside ${...} within a template literal. The expression is evaluated at runtime and its result is inserted into the string.
3

Multi-line Strings

Unlike regular strings, template literals preserve line breaks exactly as written. You can press Enter inside a backtick string and the newline becomes part of the output.
4

Automatic Type Coercion

When a non-string value (like a number or boolean) appears in a ${} placeholder, JavaScript automatically converts it to a string — no manual conversion needed.
✦ KEY TAKEAWAY
Think of a template literal like a fill-in-the-blank worksheet. The backticks are the sheet of paper, the regular text is the printed prompt, and each ${} 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.

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.

The cyan backticks delimit the template literal. Purple dashed lines mark static text, while amber dashed lines point to expressions that are evaluated at runtime. The green box at the bottom shows the final assembled string.

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.

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
`staticText${expression}moreText${expression2}end`
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
Remember that statements (like 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.

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.

The red box (left) uses old-style concatenation with multiple quote marks and plus signs. The green box (right) achieves the same result with a single template literal — fewer characters, fewer chances for error, and the code looks almost identical to the desired output.
Key differences between concatenation and template literals
FeatureConcatenationTemplate Literal
Delimiter"..." or '...'`...`
Embed a variable"Hi " + name`Hi ${name}`
Multi-lineRequires \n escapeJust press Enter inside the backticks
ExpressionsBreak out of string, compute, re-enter stringWrite the expression directly inside ${}
ReadabilityDecreases as complexity growsStays high — code mirrors the output

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 VariablesStart 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 GradeUse 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 LiteralNow 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 Outputconsole.log(report); The console displays: Report Card ----------- Student: Priya Score: 87/100 Grade: B Points to A: 3
A clean, readable, multi-line report — built with zero concatenation operators.
💡 Try It Yourself
Open your browser's developer console (press F12, then click the Console tab) and paste the code from each step. Change studentName and score to your own values and watch the output update.

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 vs. limitations of template literals
Strengths ✅Limitations ⚠️
Dramatically improves readability for dynamic stringsCannot use statements (if, for, while) inside ${} — only expressions
Multi-line strings without \n escapesExtra whitespace and indentation inside backticks become part of the string — can cause unexpected formatting
Supports any valid expression, including function callsVery complex expressions inside ${} can hurt readability — extract into a variable first
Automatic type coercion converts numbers and booleans to stringsNot supported in Internet Explorer (though IE is effectively retired)
🎯 BEST PRACTICE
Use template literals whenever you need to combine text with variable data. However, keep expressions inside ${} 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.

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.

Untagged vs. tagged template literals
FeatureUntagged (This Lesson)Tagged (Advanced)
Syntax`Hello ${name}`myTag`Hello ${name}`
Who builds the final string?The JavaScript engine, automaticallyYour custom myTag function
Use casesGeneral-purpose string formattingHTML sanitization, internationalization, CSS-in-JS (e.g., styled-components)
When to learnNow — foundational skillAfter mastering functions and arrays

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.

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.

PROBLEM 1 — CONCEPTUAL
What character is used to delimit a template literal, and what symbol marks the beginning of an embedded expression? Explain why using these differs from regular string concatenation.
PROBLEM 2 — BASIC CALCULATION
Given 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.
PROBLEM 3 — INTERMEDIATE
Rewrite the following concatenation as a template literal: "Welcome, " + user + "!\nYou have " + msgs + " unread message" + (msgs !== 1 ? "s" : "") + "." Make sure your version handles the plural "s" correctly using a ternary expression inside ${}.
PROBLEM 4 — APPLIED
You are building a weather app. You have three variables: 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°C
PROBLEM 5 — CRITICAL THINKING
A classmate writes the following code and is confused about the output: 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 ${}?

Lesson 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.

Varsity Tutors • Computer Programming 1 (JavaScript) • Template Literals