Template Literals
Template literals are string literals that allow for embedded expressions. They were called template strings prior to ES2015 (ES6). Template literals are enclosed in back ticks.Expressions are indicated with the dollar symbol and enclosed in curly braces. They are useful because you do not need to concatenate several strings to make your sentence and add syntactic sugar for easier readability. See the code snippets below.
Syntax
1
2
3
4
5
6
7
8
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
tag `string text ${expression} string text`
Example 1
1
2
3
4
5
var x = 10;
var y = 5;
console.log("The product of " + x + " and " + y + " is " + (x * y));
//The product of 10 and 5 is 50
1
2
3
4
5
var x = 10;
var y = 5;
console.log(`The product of ${x} and ${y} is ${x * y}`)
//The product of 10 and 5 is 50
The two code snippets above are equivalent, however the the second one using template literals are easier to write since you eliminate having to add quotes and plus symbols between expressions. It is also a lot easier to read and will decrease syntax errors.
Let’s take a look at a more advanced example. See the code snippet below. We are accessing an object’s key values and are even able to use methods on them as expected. Also notice that a line break is easily achieved without any special escape characters. If you need to include a backtick in your string you can use the escape character backslash, `\ .
Example 2
1
2
3
4
5
6
7
8
9
10
11
var coder = {
name: "richard",
age: 35,
bootcamp: "telegraph academy",
cohort: 5,
};
console.log(`${coder.name.toUpperCase()} is ${coder.age} and
enrolled at ${coder.bootcamp} in the {coder.cohort}th cohort`);
//RICHARD is 35 and
//enrolled at telegraph academy in the 5th cohort
There is another feature called tagged template literals. A tag function is a function that will process and interpret a template. The tag appears in front of the template literal. The tag functions ability to modify output is powerful because it can do things like encode a URL. See the code snippet below for a simple example of a tag function, upper, and a template literal.
Example 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
let upper = function(strings, ...values){
let result = "";
for(let i = 0; i < strings.length; i++){
result += strings[i];
if(i < values.length){
result += values[i];
}
}
return result.toUpperCase();
};
var a = "ba";
var b = "na";
var c = 1;
var d = 2;
var banana = upper`i ate ${c+d} ${a}${b}${b}s!`
console.log(banana);
//I ATE 3 BANANAS!
Now that you have learned an easier way to write strings, it should save you time and frustration as you move forward with your projects!