Backticks JavaScript? Meet JavaScript template literals

Learn how to use template literals in Javascript to make working with strings easier.
Published 2023-04-01 4 min read
Backticks JavaScript? Meet JavaScript template literals

Strings in JavaScript are pretty basic, for many years text operations were limited. But when it comes to strings in JavaScript there is a feature that can help you write cleaner and more readable code: template literals. Let’s dive in and see how they can improve your code.

 

What are Template Literals?

Template literals, introduced in ES6, are an elegant way to create strings dynamically in JavaScript. They provide a shorter, more readable syntax for interpolation and multiline strings. To create a template literal, you simply use backticks (“) instead of single or double quotes.

For example, here’s a regular string:

const greeting = "Hello, world!";

 

And here’s a template literal:

const greeting = `Hello, world!`;

Both look similar, but template literals are more powerful. The example above doesn’t make sense, so let’s explore the possibilities they create.

 

String Interpolation

The most useful feature of template literals is string interpolation. It allows you to embed expressions within your string, which makes it easier to create dynamic strings.

Consider the following example using string concatenation:

const name = "John";
const age = 30;
const message = "Hello, my name is " + name + " and I'm " + age + " years old.";

Now, let’s rewrite it using template literals:

const name = "John";
const age = 30;
const message = `Hello, my name is ${name} and I'm ${age} years old.`;

As you can see, the template literal version is much cleaner and easier to read. Use ${expression} to insert a variable or expression into your string.

Multiline Strings

Before template literals, creating multiline strings was a bit cumbersome. You had to use the newline character \n or concatenate strings with the + operator. Template literals simplify this process.

Here’s an example of creating a multiline string using traditional string concatenation:

const text = "Line 1\n" + "Line 2\n" + "Line 3";

Now, let’s see how to create the same multiline string using template literals:

const text = `Line 1
    Line 2
    Line 3`;

As you can see, template literals make it much easier to create multiline strings without any special characters or concatenation. The indentation is not ideal though. If you indent the code the indentation will be present in the final string.

Tagged Template Literals

Tagged template literals are an advanced feature that allows you to customize the processing of template literals by using a tag function. To be honest, it’s not used too often, but this can be helpful for tasks like sanitizing user input or localization. That’s why it’s important to remember that there is such an option.

Here’s an example of a simple tag function:

function myTag(strings, ...values) {
  let result = "";
  for (let i = 0; i < strings.length; i++) {
    result += strings[i] + (values[i] || "");
  }
  return result.toUpperCase();
}

const name = "John";
const message = myTag`Hello, my name is ${name}.`;

console.log(message); // "HELLO, MY NAME IS JOHN."

In this example, the myTag function transforms the template literal into an uppercase string. In general, this usage of a template literal will just run the tagged function with some arguments. The first one is an array of the “constant” parts from the template literal and the rest of them are expressions. This function has no obligation to return a string. That’s why it’s powerful - you can do whatever you want with each part of the template.

 

Template literals are extremely useful in day-to-day coding. That’s why you’ll see them everywhere in the codebase of most modern JS projects. Of course, remember to use them when it’s appropriate, for most cases standard JS strings are a better option, but when it comes to embedding dynamic content in the string template literals are the way to go. Also, they make it easier to build multi-line strings. Finally, you can get creative with tagged literals for text transformation. 

#javascript