Learning Template Literals
Template literals are a new form of string that was introduced in ECMAScript 6. They are enclosed by the backtick symbol (``
) instead of the usual single or double quotes. Template literals allow you to embed expressions in the string that are evaluated at runtime. Thus, we can easily create dynamic strings from variables and variable expressions. These expressions are denoted with the dollar sign and curly braces (${ expression }
). The template literal syntax is shown in the following code:
const example = "pretty"; console.log( `Template literals are ${ example } useful!!!` ); // Expected output: Template literals are pretty useful!!!
Snippet 1.22: Template literal basic syntax
Template literals are escaped like other strings in JavaScript. To escape a template literal, simply use a backslash (\
) character. For example, the following equalities evaluate to true: `\`` === "`",`\t` === "\t"
, and `\n\r` === "\n\r".
Template literals allow for multiline strings. Any newline characters that are inserted into the source are part of the template literal and will result in a line break in the output. In simpler terms, inside a template literal, we can press the Enter key on the keyboard and split it on to two lines. This newline character in the source code will be parsed as part of the template literal and will result in a newline in the output. To replicate this with normal strings, we would have to use the \n
character to generate a new line. With template literals, we can break the line in the template literal source and achieve the same expected output. An example of this is shown in the following code:
// Using normal strings console.log( 'This is line 1\nThis is line 2' ); // Expected output: This is line 1 // This is line 2 // Using template literals console.log( `This is line 1 This is line 2` ); // Expected output: This is line 1 // This is line 2
Snippet 1.23: Template literal multi-line syntax
Exercise 5: Converting to Template Literals
To convert standard string objects to template literals to demonstrate the power of template literal expressions, perform the following steps:
Create two variables,
a
andb
, and save numbers into them.Log the sum of
a
andb
in the formata + b
is equal to<result>
using normal strings.Log the sum of
a
andb
in the formata + b
is equal to<result>
using a single template literal.
Code
index.js:
let a = 5, b = 10; console.log( a + ' + ' + b + ' is equal to ' + ( a + b ) ); console.log( `${a} + ${b} is equal to ${a + b}` );
Snippet 1.24: Template literal and string comparison
Outcome
You have successfully converted standard string objects to template literals.
Template literals allow for expression nesting, that is, new template literals can be put inside the expression of a template literal. Since the nested template literal is part of the expression, it will be parsed as a new template literal and will not interfere with the external template literal. In some cases, nesting a template literal is the easiest and most readable way to create a string. An example of template literal nesting is shown in the following code:
function javascriptOrCPlusPlus() { return 'JavaScript'; } const outputLiteral = `We are learning about ${ `Professional ${ javascriptOrCPlusPlus() }` }`
Snippet 1.25: Template literal nesting
A more advanced form of template literals are tagged template literals. Tagged template literals can be parsed with a special function called tag functions, and can return a manipulated string or any other value. The first input argument of a tag function is an array containing string values. The string values represent the parts of the input string, broken at each template expression. The remaining arguments are the values of the template expressions in the string. Tag functions are not called like normal functions. To call a tag function, we omit the parentheses and any whitespace around the template literal argument. This syntax is shown in the following code:
// Define the tag function function tagFunction( strings, numExp, fruitExp ) { const str0 = strings[0]; // "We have" const str1 = strings[1]; // " of " const quantity = numExp < 10 ? 'very few' : 'a lot'; return str0 + quantity + str1 + fruitExp + str2; } const fruit = 'apple', num = 8; // Note: lack of parenthesis or whitespace when calling tag function const output = tagFunction`We have ${num} of ${fruit}. Exciting!` console.log( output ) // Expected output: We have very few of apples. Exciting!!
Snippet 1.26: Tagged template literal example
A special property named raw
is available for the first argument of a tagged template. This property returns an array that contains the raw, unescaped, versions of each part of the split template literal. This is shown in the following code:
function tagFunction( strings ){ console.log( strings.raw[0] ); } tagFunction`This is line 1. \n This is line 2.` // Expected output: "This is line 1. \n This is line 2." The characters //'\' and 'n' are not parsed into a newline character
Snippet 1.27: Tagged template raw property
In summary, template literals allow for the simplification of complicated string expressions. Template literals allow you to embed variables and complicated expressions into strings. Template literals can even be nested into the expression fields of other template literals. If a template literal is broken into multiple lines in the source code, the interpreter will interpret that as a new line in the string and insert one accordingly. Template literals also provide a new way to parse and manipulate strings with the tagged template function. These functions give you a way to perform complex string manipulation via a special function. The tagged template functions also give access to the raw strings as they were entered, ignoring any escape sequences.
Exercise 6: Template Literal Conversion
You are building a website for a real estate company. You must build a function that takes in an object with property information and returns a formatted string that states the property owner, where the property is located (address
), and how much they are selling it for (price
). Consider the following object as input:
{ address: '123 Main St, San Francisco CA, USA', floors: 2, price: 5000000, owner: 'John Doe' }
Snippet 1.28: Object Input
To utilize a template literal to pretty-print an object, perform the following steps:
Create a function called
parseHouse
that takes in an object.Return a template literal from the function. Using expressions, embed the owner, address, and price in the format
<Owner> is selling the property at <address> for <price>
.Create a variable called
house
and save the following object into it:{ address: "123 Main St, San Francisco CA, USA", floors: 2, price: 5000000, owner: "John Doe" }
Call the
parseHouse
function and pass in thehouse
variable.Log the output.
Code
index.js:
function parseHouse( property ) { return `${property.owner} is selling the property at ${property.address} for ${property.price} USD` } const house = { address: "123 Main St, San Francisco CA, USA", floors: 2, price: 5000000, owner: "John Doe" }; console.log( parseHouse( house ) );
Snippet 1.29: Template literal using expressions
Outcome
You have successfully utilized a template literal to pretty-print an object.
In this section, we covered template literals. Template literals upgrade strings by allowing us to nest expressions inside them that are parsed at runtime. Expressions are inserted with the following syntax: `${ expression }`
. We then showed you how to escape special characters in template literals and discussed how in-editor newline characters in template literals are parsed as newline characters in the output. Finally, we covered template literal tagging and tagging functions, which allow us to perform more complex template literal parsing and creation.