Course: Section

Get Started with Modern React: Intro, Setup, and ES6 Basics

Episode: Title

S01・V08: Template Literals

Date Created: July 17th, 2019
Last Updated: 27 days ago

Objectives
  1. We will explain what “template literals” are.
  2. We will use them to wrap multi-line strings, preserving any new lines and whitespace.
  3. We will use them to do string interpolation, which allows us to embed expressions in strings.
Watch Video
Duration: 3m 35s

Template Literals

Template literals were introduced in JavaScript ES6. Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

Template literals are enclosed by the back-tick character instead of double or single quotes. We will show you an example.

const t = `This is a template literal`;

console.log(t);

In this example, the template literal is a simple string.

Multi-Line String

Any newline characters inserted in a multi-line string are part of the template literal.

const t = `This is a
multi-line text
string.`;

console.log(t);

In this example, we can see that the multi-line template literal preserves the newlines.

String Interpolation

Template literals can contain placeholders. These are indicated by the dollar sign and curly braces: ${}:

const placeholder = "React";
const t = `We love ${placeholder}!`;

console.log(t); // Prints `We love React!`

The value of the variable in the placeholder and the text between the back-ticks are concatenated into a single string.

We can evaluate any JavaScript expressions within the dollar-curly-braces placeholder. For example:

const a = 2;
const b = 3;

const t = `The sum of ${a} and ${b} is ${a + b}.`;

console.log(t); // Prints `The sum of 2 and 3 is 5.`

In the third placeholder, the expression a + b, is evaluated, and its result is placed in the string output.

Finally, we will show an example that combines the multi-line and string interpolation features of template literals.

const a = 5;
const b = 3;

const t = `The expression a + b * 2
where a = ${a} and b = ${b}
equals ${a + b * 2}, not ${(a + b) * 2}.`;

console.log(t);

The console.log() shows the interpolated multi-line string output.

Summary

We explained what “template literals” are. We used them to wrap multi-line strings, preserving any new lines and whitespace. And, we used them to do string interpolation, which allows us to embed expressions in strings.

Next Up…

In the next video, we will look at functions in detail.