Using Template Literals

Single quotes and double quotes are used interchangeably in JavaScript, and both can only contain string literals. To embed the value of a variable or a result of an expression into a string, we traditionally used + to concatenate. But that can get verbose and noisy, as in the following example.

 const​ name1 = ​'Jack'​;
 const​ name2 = ​'Jill'​;
 
 console.log(​'Hello '​ + name1 + ​' and '​ + name2);

Code with multiple +s often gets unwieldy, unpleasant, hard to maintain, and boring to write. This is where template literals come in.

Template Literals

Template literals are strings with embedded expressions. The expressions may be a single variable, multiple variables with operators, a function call, or combinations of them—any valid JavaScript expression.

In languages like Ruby and Groovy, single quotes are used for string literals and double quotes for template literals. Since JavaScript has used both single and double quotes for string literals, it’s too late to change the behavior or the semantics of either one. Thus, JavaScript has introduced a new syntax for template literals: the backtick.

Let’s convert the last line of the previous code to use a template literal instead of the multiple + operator.

 console.log(​`Hello ​${name1}​ and ​${name2}​`​);

The output of this line of code is the same as the last line of code from the previous code snippet:

 Hello Jack and Jill

Syntax of Template Literals

Within the pair of backticks, string literals appear as is. Expressions, on the other hand, appear within ${}. The curly braces {} surrounding the expressions in template literals are not optional. Without them, the expressions are treated as string literals. For example, let’s remove {} in the second expression of the previous line of code:

 console.log(​`Hello ​${name1}​ and $name2`​);

Here’s the result:

 Hello Jack and $name2

Don’t forget to embed the expressions with {} and also prefix with $.

You can use a backslash to embed a backtick within a template literal. For example, ‘“ will result in . Single and double quotes may also appear within template literals, like so:

 const​ item = ​'cake'​;
 console.log(​`The kid asked, "how's the ​${item}​?"`​);

Template literals preserve the quotes, as we see from the following output:

 The kid asked, "how's the cake?"

The combination of ${ causes template literals to treat what follows as an expression. The appearance of one or the other of those two symbols alone will be treated as literals, like so:

 const​ price = 1;
 console.log(​`The price of a { symbol is $​${price * 0.01 }​.`​);

The output shows that the first { and the first $ appear as is:

 The price of a { symbol is $0.01.

Template literals may include function calls as well, like so:

 console.log(​`Shout out greetings: ​${​'hello'​.toUpperCase()}​`​);

const, let, and Template Literals

In the examples so far, the variables used in template literals were declared as const. However, they may be declared using let as well, but use caution as this may lead to confusion. For example, try to determine the output of the following code without running it:

 let​ value = 4;
 
 const​ msg1 = ​`The value is ​${value}​`​;
 const​ print = () => ​`The value is ​${value}​`​;
 
 value = 0;
 
 console.log(msg1);
 console.log(print());

The expressions within template literals are evaluated when the template literal is evaluated. As a result, msg1 will contain the value 4. However, since the template literal within the arrow function will be evaluated later, only when the function is invoked, the value there will be zero. This is because the value has changed by the time that template literal is evaluated. We can see this from the output:

 The value is 4
 The value is 0

This is another reminder why we should honor immutability wherever possible—see Perils of Mutability and Prefer const over let.

Nested Template Literals

Template literals may be nested as well. Here’s an example of nesting one template literal within another:

 const​ hours = 14;
 const​ event = ​'meeting'​;
 
 console.log(​`The ​${event}​ will happen ​${hours < 12 ? ​'in the morning'​ :
 `later in the day, in the ​${hours < 20 ? ​'evening'​ : ​'night'​}​`​}​.`​);

The top-level template literal relies on the nested template literal to create a string with an alternative embedded word “evening” or “night.” The output of this code is

 The meeting will happen later in the day, in the evening.

Use your judgment to decide if after nesting template literals the code is readable or hard to understand. If it is the latter, then break the nested template literal into a separate regular function or an arrow function, like so:

 const​ when = (hrs) =>
  hrs < 12 ? ​'in the morning'​ :
 `later in the day, in the ​${hrs < 20 ? ​'evening'​ : ​'night'​}​`​;
 
 console.log(​`The ​${event}​ will happen ​${when(hours)}​.`​);

If you decide to use nested literals, then inserting line breaks, as in the previous nested example, may help improve readability. That brings us to the next topic: multiline strings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset