JavaScript Template Literals (Template String)

In this section, we will learn what the template literals are and how to use them in JavaScript.

What is JavaScript Template Literals? (JavaScript String Interpolation)

Template literals provide a way to create strings (and other things which we will get into it in just a moment) using a literal syntax, combining text and embedded substitutions.

Template literals come in two forms: `untagged` and `tagged`. The first one will be introduced in this section and the second one you’ll learn about in the `tag function` section.

An untagged template literal creates a string.

Take a look at this example:

console.log(`Hi my name is John Doe`);

So far, that doesn’t seem to offer anything that a string literal doesn’t, but template literals have several handy features.

Within a template literal, we can use `substitutions` to add content from any expression.

JavaScript Template Literals Substitution Syntax:

Here’s the syntax of a substitution in the template literal:

${}

A substitution starts with a dollar sign `$` immediately followed by an opening curly brace `{` and ends with a closing curly brace `}`.

Everything between the curly braces is the body of the substitution. The expression here in this body will be evaluated when the template literal is evaluated. At the end, the result will be used in place of the substitution.

Example: string interpolation in JavaScript

const firstName = "John";
const lastName = "Doe"
console.log(`Hi, my name is ${firstName} ${lastName}`);

Output:

Hi, my name is John Doe

Note: the result of a substitution will always be a string (if the value is not a string already, it will be converted).

JavaScript Template Literals escaping the dollar sign

If we need the actual dollar sign followed by a curly brace in a template literal, we can escape the dollar sign as the example below shows:

console.log(`Not a substitution: \${foo}`); //Not a substitution: ${foo}

But remember: we don’t need to escape dollar signs unless they’re followed by an opening curly brace.

JavaScript Multiline String

Another handy feature is that unlike string literals, template literals can contain unescaped newlines, which will be retained in the template.

Example: creating multiline string via template literals in JavaScript

const firstName = "John";
const lastName = "Doe"
console.log(`Hi, my name is ${firstName}
                ${lastName}`);

Output:

Hi, my name is John

Doe

JavaScript Tag Function

This is explained in the JavaScript Tag Function section.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies