Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 156 ยท Data Types

Template Literals

Build strings the modern way with JavaScript template literals. Learn ${} interpolation, multi-line strings, embedded expressions and tagged templates.

Sooner or later every program needs to glue values into text: a greeting with a user's name, a price with a currency sign, a log line with a timestamp. With plain quotes you do that with +, and the result quickly turns into a jumble of quotes, spaces and plus signs.

Template literals fix this. They are strings written between backticks (`) instead of quotes, and they can contain placeholders that JavaScript fills in for you. They also span several lines without any escape characters, and an advanced form called tagged templates lets a function process the pieces. This lesson covers all three.

Backticks and placeholders

A template literal looks like a normal string, but with backticks. Inside it, ${ ... } marks a placeholder. JavaScript evaluates whatever is between the braces and inserts the result into the string:

JS Your first template literal

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both lines produce the exact same string, but the template literal reads like the sentence it creates. You can see where every space goes, and you never have to close and reopen quotes.

A template literal without any placeholders is just a string. `hello` and "hello" are identical values, and typeof reports "string" for both. Use whichever reads best; many style guides keep quotes for plain text and backticks for text with placeholders.

Typing a backtick: on US keyboards the backtick sits to the left of the 1 key. On many European layouts it is a "dead key" โ€” press it, then press Space to get the character on its own.

Any expression can go inside ${}

A placeholder is not limited to variable names. It accepts any expression: arithmetic, function calls, property lookups, method calls, even another template literal. (Statements such as if or for are not allowed, because they don't produce a value.)

JS Expressions in placeholders

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice $${...} in the second line: the first $ is an ordinary character, and only ${ starts a placeholder. The third-to-last line uses the conditional (ternary) operator, which you will meet properly in The Ternary Operator and switch. It is handy in templates because it is an expression.

Whatever a placeholder produces is converted to a string. Numbers and booleans become their usual text. Arrays are joined with commas. A plain object becomes [object Object], which is almost never what you want:

JavaScript
const tags = ["red", "round", "ripe"];
const fruit = { name: "apple" };

`Tags: ${tags}`;                    // "Tags: red,round,ripe"
`Fruit: ${fruit}`;                  // "Fruit: [object Object]"
`Fruit: ${JSON.stringify(fruit)}`;  // 'Fruit: {"name":"apple"}'
`Values: ${null} and ${undefined}`; // "Values: null and undefined"

When you see [object Object] in your output, a template literal (or +) received an object. Pick the property you meant, or convert it with JSON.stringify(). Keep placeholders short: if an expression grows long, compute it into a well-named variable first.

Multi-line strings

A quoted string must end on the line where it started; to add a line break you write the escape \n. A template literal can simply continue onto the next line, and the line breaks become part of the string:

JS Multi-line text

Press Run (or Ctrl + Enter) to see the console output here.

No output.

There is one catch: every character between the backticks counts, including the indentation. If you indent the lines to match your code, the spaces end up in the string:

JavaScript
function receipt() {
  const text = `Line one
    Line two`;   // this line starts with 4 spaces
  return text;
}

For short text that is fine. For longer blocks, either start the extra lines at the left edge, or build the text from an array of lines with .join("\n").

Escapes still work inside template literals: \n, \t, \\ and the rest from Strings. To include a literal backtick, write \`. To show the characters ${ without starting a placeholder, escape the dollar sign: \${.

Building HTML snippets

Template literals are popular for building small chunks of HTML, because the markup keeps its shape:

JavaScript
const product = { name: "Notebook", price: 4.99 };

const card = `
  <article class="card">
    <h3>${product.name}</h3>
    <p>$${product.price}</p>
  </article>`;

This is convenient, but be careful where the values come from. If product.name contains text typed by a user, inserting it into HTML can let that user inject their own markup or scripts (an attack called cross-site scripting, or XSS). You will learn safe ways to put text on a page in Changing Content. For now, remember: templates insert text exactly as it is โ€” they don't escape anything for you.

Tagged templates

So far the template literal itself built the string. A tagged template hands the pieces to a function instead. You write the function name directly before the backtick, with no parentheses:

JavaScript
tag`Hello ${name}!`

JavaScript calls tag with two kinds of arguments:

  1. An array of the literal text pieces โ€” the parts between the placeholders.
  2. The values of the placeholders, one argument each.

There is always exactly one more text piece than there are values (the pieces at the start or end may be empty strings). The tag can return anything it likes. Here is one that shows what it receives, and one that does something useful with it:

JS Writing tag functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The ...values syntax collects the remaining arguments into an array; it is called a rest parameter and is covered in Parameters and Arguments. The loop pattern in highlight โ€” start with the first piece, then alternate value, piece, value, piece โ€” is the backbone of almost every tag function.

Tags are the reason template literals are so flexible. Libraries use them to escape HTML safely, to build database queries where values can't break the SQL, to write CSS inside JavaScript, and to translate text. You won't write tags every day, but you will recognize them when you see a function name glued to a backtick.

String.raw

JavaScript ships with one built-in tag, String.raw. It returns the text with escape sequences left untouched, so a backslash stays a backslash:

JS String.raw keeps backslashes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first line prints a line break and a tab, because \n and \t are escape sequences. String.raw keeps them as typed, which makes it handy for Windows paths and for regular expressions that are full of backslashes. Placeholders still work inside it.

When to use which quotes

  • Use template literals whenever you insert values or need several lines.
  • Use single or double quotes for plain fixed text if your team prefers โ€” they are slightly easier to type and signal "nothing dynamic here".
  • Avoid long chains of + for building text. They are harder to read and easy to get wrong (a missing space, a number accidentally added instead of joined).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does `Sum: ${2 + 3}` evaluate to?

    The placeholder holds an expression. 2 + 3 is evaluated to 5, then converted to text.
  2. 2. A template literal inserts a plain object, ${user}. What text appears?

    Objects are converted with their default toString(), which gives [object Object]. Insert a property, or use JSON.stringify().
  3. 3. Which statement about multi-line template literals is true?

    Everything between the backticks is kept, including line breaks and leading spaces.
  4. 4. In tag`a${x}b${y}c` , what is the first argument passed to tag?

    The first argument is the array of literal pieces; the placeholder values follow as separate arguments.

Summary

  • Template literals are strings in backticks; ${expression} inserts the value of any expression.
  • Inserted values are converted to strings โ€” watch out for [object Object] when you insert an object.
  • They can span several lines; line breaks and indentation are kept exactly.
  • Templates don't escape HTML for you, so be careful with user input.
  • A tagged template (tag`...` ) calls a function with the text pieces and the values; String.raw is the built-in tag that keeps backslashes.

Next: Booleans and Truthiness โ€” true, false and how every value behaves in a condition.