Template Strings using Backticks (`) in Javascript

By Mike Sharp
21 March, 2021

Github icon
Back to posts

tldr? Prefer moving pictures instead? we've got you covered, here's the video version of this blog.

Today's topic: Template Strings

Today we're going to look at Template Strings, also known as "Template Literals" or "Backtick Strings".

Template Strings are written using backticks (`) instead of the quotes that are normally used when you write out a string.

We'll explore how they differ from regularly quoted strings and why you might want to use them instead.

Why Template Strings?

So, why do we need another way to write strings?

Aren't quotes enough to get the job done?

Well, there are a couple of scenarios where using standard quoted strings can get messy.

let's take a look at an example.

Handling multi-line strings

So we're going to write out a Javascript string of HTML to add dynamically to the web page.

The HTML is going to contain a heading, a paragraph and a couple of buttons.

It would be nice to retain the formatting and structure of the HTML and keep it split up on multiple lines to make it easier to read and change

The only way you can do that with quoted strings is to split each line into separate strings and then concatenate or stitch together the strings with the + operator.

window.document.body.innerHTML =

"<h1>About Us</h1>" +
"<p>" +
"<span>Hello there, welcome to our site!</span>" +
+ "<br />" +
"<span>Click these buttons</span>" +
"<br />" +
'<button type="button">Button 1</button>' +
'<button type="button">Button 2</button>' +
"</p>";

};

Mixing data into the string

We also want to add some variables into the HTML before we render it, so we're going to have to break the collection of strings even more and concatenate them back together again.

const username = "Mike";
const confirmAction = "Go on, confirm!";
const cancelAction = "Go back, now!";
window.document.body.innerHTML =
  "<h1>About Us</h1>" +
  "<p>" +
  "<span>Hello there " +
  username +
  ", welcome to our site!</span>" +
  "<br />" +
  "<span>Click these buttons</span>" +
  "<br />" +
  '<button type="button">' +
  confirmAction +
  "</button>" +
  '<button type="button">' +
  cancelAction +
  "</button>" +
  "</p>";

This is starting to get a bit messy and unwieldy, isn't it?

There must be a better way, right?

Well, now there is!

Enter Template Strings

Template Strings have been added to JavaScript to address the problems just explored:

  • Handling strings that span multiple lines (that may also contain indentation)
  • Mixing (or interpolating) JavaScript variables and statements into strings.

Let's take a deeper look.

Features of Template Strings

Multi-line support

Using Template Strings is simple.

Instead of needing to break all of these lines of HTML up into separate strings, you can just surround the whole thing in backticks ` and remove all of the extra quotes " and + symbols from the code.

The result is one multi-line string wrapped in backticks.

window.document.body.innerHTML = `
<h1>About Us</h1>
<p>
  <span>Hello there, welcome to our site!</span>
  <br />
  <span>Click these buttons</span>
  <br />
  <button type="button">Button 1</button>
  <button type="button">Button 2</button>
</p>`;
};

It's much easier to read and we no longer have to worry about whether we missed a "plus symbol" symbol or opening or closing quote.

The indentation of the HTML is also properly represented when written as a Template String.

But how can we mix variables with Template Strings? let's take a look.

String interpolation

In the HTML scenario we discussed earlier, we would've had to break up our strings into multiple strings to allow us to add variables in-between the HTML.

Using a template string we can go ahead and join all of these regular strings back together and then surround any variables we want to get the value for with dollar, opening brace and then closing brace ${} to interpolate or mix those our variables into the string.

const username = "Mike";
const confirmAction = "Go on, confirm!";
const cancelAction = "Go back, now!";

window.document.body.innerHTML = `

<h1>About Us</h1>
<p>
  <span>Hello there ${username}, welcome to our site!</span>
  <br />
  <span>Click these buttons</span>
  <br />
  <button type="button">${confirmAction}</button>
  <button type="button">${cancelAction}</button>
</p>`;
};

When the string is rendered, we can see it includes the values we specified using the dollar and braces ${}

This is because anything contained within a dollar and braces is evaluated as a JavaScript expression and the result of the expression is output into the final string.

Nesting statements

We're not just limited to mixing variables into Template Strings, we can also add conditional statements, or indeed any kind of a JavaScript statement or expression that yields in a value.

All we have to do is add the statement inside the dollar-braces ${} and we're good to go.

In the example below, the rendered value alternates based on the conditional statement that's been added between the dollar and braces.

The conditional statement decides whether the word "even" or "odd" is output based on whether the for loop variable is even or odd.

for (let i = 0; i < 5; i++) {
  window.document.body.innerHTML += `
    <p>
      number is ${i % 2 === 0 ? "even" : "odd"}
    </p>
  `;
}

String interpolation and nesting are versatile and powerful.

The resulting code is much easier to read through than using multiple traditional strings and string concatenation.

Template Strings bonus features

Template Tagging Functions

When a template string gets prefixed with the name of a function, this is called tagging.

By tagging the template string, we're telling JavaScript to run that function, using the string as an input, along with all of the variables defined in the template.

The final output is a string that's been modified by the function we tagged the template with.

Here's the odd-even example from earlier, but implemented using tagging.

function oddEven(stringFragments, counterArg) {
  const counterOddOrEven = counterArg % 2 === 0 ? "Even" : "Odd";
  return `${stringFragments[0]} ${counterOddOrEven} ${stringFragments[1]}`;
}

for (let i = 0; i < 5; i++) {
  window.document.body.innerHTML += oddEven`
  <p>
    number is ${i}
  </p> 
  `;
}

As you can see, all of the logic to decide whether the number is or even has been extracted out of the string and has been replaced with a tagging function.

The first argument in the tagging function (stringFragments in the example above) is an array of all of the string fragments within the template, all subsequent arguments are the dollar-braced ${} expressions that are in the template (we have one argument called counterArg to represent the count we want to test for odd-ness or even-ness)

Tagging functions let us take the logical complexity out of the template string and move it into a purpose-built function to de-clutter and improve the clarity of the string.

You can use the same tagging function in multiple places whenever you need to, so it's good for code re-use too.

Quirks of Template Strings and gotchas to watch out for

Template Strings are simple to use and I encourage you to start using them in your projects today, but there are a few things to consider before you use them everywhere.

Browser support for Template Strings

Template string syntax is widely supported in the latest versions of the most popular browsers, so if that's your target audience then you should start using Template Strings right away.

If you need to support legacy browsers, please be aware that:

  • Template Strings cannot be poly-filled for older browsers, they will cause JavaScript errors if used in programs run in older browsers like Internet Explorer or really out of date builds of the more popular browsers
  • You can mitigate this by using a transpiler such as Babel, but it's highly recommended you use Template Strings natively if you only need to support modern browsers

When to use Template Strings and when not to

So now you know all about Template Strings, where does this leave you with plain old quotes?

Use Template Strings when you want to define a multi-line string

You should use Template Strings over traditional quoted strings when you need to break your code up onto multiple lines.

If a string is large or you want to retain the formatting to better convey a structure in your code by splitting it onto multiple lines, you should use Template Strings instead of quoted strings.

Use Template Strings when you want to combine variables or logical statements with your string

If you're mixing any kind of data or logic into a string you want to use Template Strings instead of quoted strings.

Building a template a string with interpolated values, nested logic or using a tagging function is so much easier to read and comprehend compared to a nest of concatenated strings combined with inline spaghetti code on single lines.

In terms of readability, Template Strings are a clear winner in this scenario by far.

Regular strings still have their purpose

There is one caveat, while you could use backticks for every string you write, the current convention is to use them only when you need multi-line support or need to mix data or logic into a string.

Keep using quoted strings when your string is on a single line and no data or logic needs interpolating.

Exercising moderation around using Template Strings will make the template string code stand out better from all of the other strings in your application and will make your code easier to scan and read.

Although this is just a rule of thumb, nothing is stopping you from using Template Strings for every string you write.

Have I convinced you to use Template Strings yet?

Template Strings are a great way to make writing multi-line or logic-dependent strings simpler to write and make the resulting code much easier to understand should you ever need to come back and make changes.

Start using Template Strings in your projects today.

Trust me, you'll never want to go back to adding plus symbols to complex strings everywhere and spending half an hour looking for that quote or + symbol that you missed out on.

If you liked this blog, there's also a video version here