JavaScript Template Literals

Up until now, we only had two ways to write a string in JavaScript – single and double quotes. If we wanted to interpolate a variable with one of these string options, we’d need to break out of the string and concatenate the variable.

As of ES2015, we are able to use Template Literals (AKA Template Strings). These are string literals that allow embedded expressions.

Instead of single or double-quoted strings, we can enclose our strings with back-ticks, which allows for variable interpolation without breaking out of the string.

For example:

const petName = 'Tucker';
const petAge = 9;
const petType = 'dog';
const petAbout = `My ${petType} ${ petName } is ${ petAge * 7 } years old, in dog years.`;

Multi-line strings

In addition to interpolation, another feature of Template Literals, that wasn’t available before, is that you can now easily create multi-line strings without having to escape them.

Prior to this feature, you needed to escape each return, as follows:

const markup = "This is \
    a multi-line string. The \
    returns need to be escaped with \
    slashes and you can not interpolate \

HTML fragments

This is handy when creating HTML markup to output as a string. Note that the whitespace will be output as well, but this isn’t really problematic since the whitespace is ignored as soon as it hits the HTML.

const pet = {
    name: 'Tucker',
    type: 'Dog',
    breed: 'Shih Tzu',
    bio: 'Tucker is a sweet and snuggly little pup ... and also very needy.',

const markup = `
    <div class="pet">
      <p class="type">Type: ${pet.type}</p>
      <p class="breed">Breed: ${pet.breed}</p>
      <p class="bio">About ${}: ${}</p>

Nested template literals

The last thing to note here is that you can nest template literals within each other by wrapping the nested templates in the same ${} placeholder that we use to interpolate variables.

const pets = [
    { name: 'Tucker', type: 'dog', age: 9, }
    { name: 'Remy', type: 'dog', age: 11, }
    { name: 'Frank', type: 'dog', age: 4, }
    { name: 'Garfield', type: 'cat', age: 41, }
    { name: 'Rudolph', type: 'reindeer', age: 81, }

const markup = `
    <ul class="pet">
      ${ pet => `<li>${ } is a ${ pet.age } year old ${ pet.type }</li>` ).join( '' ) }

In the example above we have a template string that is nested inside a template string. With this, we can easily loop over and render the list items without breaking out of the containing string.

Side note: since map() returns an array, we pass it to join() and join it on an empty string to get rid of the commas in the output.

References & Resources

%d bloggers like this: