Getting Started with Modern JavaScript — Template Literals

Getting Started with Modern JavaScript — Template Literals

Introduced in 2015 with ECMAScript6, template literals let us dynamically construct strings of text and embedded expressions, even multi-line strings of text, in a more elegant way than concatenation.

The syntax is not much different from the old one at first glance:

const newWay = `is cool`;

Can you spot the difference? Instead of single '' or double "" quotes we use backticks ``.

String Interpolation

In ES5 you had string concatenation:

const name = 'Jack';
const old = 'My name is '+ name + '.';

Using + for both addition and concatenation can be confusing and even lead to unexpected bugs:

var a = 4;
var b = 2;

console.log('a + b = ' + a + b);
// -> a + b = 42

Template literals provide an easy way to interpolate variables and expressions into strings. The curly braces accept any valid JavaScript expression inside the ${}:

const name = 'Jack';
const str = `My name is ${name}.`;
console.log(str);
// -> My name is Jack.

const a = 4;
const b = 2;
console.log(`a + b = ${a + b}`);
// -> a + b = 6

Multiline

In ES5 you had to use the newline character \n explicitly for line breaks and the \ character at the end of a line to be able to write multi-line strings. This allows to create a string on two lines:

const concatenation = 'First line\n \
second line';

Template literals make multi-line strings simpler. Once a template literal is opened with the backtick, you press enter to create a new line, with no special characters, and it’s rendered as-is:

const interpolation = `This
is more fun!

We can add expressions!
a + b = ${a + b}`

Tagged Templates

A not as known feature that comes along with template literals, is the ability to tag them. A tagged template is a function that allows you to parse template literals, which allows us to control the string creation.

The way the tag template works is that you put the name of the function that you want to run against the string before the template. So instead of function() you have function`` .

function hi() {
  return 'TODO';
}

const name = 'Jack';
const tag = hi`My name is ${name}.`;
console.log(tag);
// -> 'TODO'

The tag template is equivalent to the following function call:

hi(['My name is ', '.'], name);

First, we get an array of all the string pieces from our literal. After that, we get all the interpolated values. Here we only have one, the name.

So then we would need to change our function to accept these arguments and return the string as we like it:

function hi(strings, name) {
  return `Hello ${name}!`;
}

const name = 'Jack';
const tag = hi`My name is ${name}.`
console.log(tag);
// -> 'Hello Jack!'

You can also alter the strings depending on the arguments, which is where the true power of tagged templates comes through. There are popular libraries like styled-components and lit-html using tagged components.

Conclusion

We have learned how template literals make strings easier to handle. They can take care of our variables and embedded expressions with ease. This is much more powerful than the old concatenation of strings and variables. And we also took a look into tagged templates and how they can let us manipulate the template literals before the browser exposes them to the world.

Did you find this article valuable?

Support Michael Karén by becoming a sponsor. Any amount is appreciated!