Lesson Tuesday

Template literals are a spoonful of syntactic sugar and another popular feature in ES6. They’re especially useful when concatenating strings or inserting variables into strings. Here’s an example of how we’d do this prior to ES6. (Ignore the fact that we wouldn’t use let prior to ES6…)

let language = "JavaScript"
let adjective = "fun"

let concatenatedString = language + " is " + adjective + " to learn!"

String concatenation is useful but quickly becomes painful. We can make this process relatively painless using template literals. Here’s an example using the same variables from above:

let stringLiteral = `${language} is ${adjective} to learn!`

This is very similar to string interpolation in Ruby. It’s also a lot easier to use than concatenation, especially with longer strings. There are two syntax rules to remember with template literals. First, we need to surround the string with the backtick symbol instead of quotes. Second, any variable or expression needs to be put inside of ${ }.

Note that ${ } can contain any expression, not just a variable. For instance, we could do this:

let length = 2;
let width = 3;
let rectangleArea = `The area of a rectangle with length ${length} and width ${width} is ${length * width}.`

In the example above, we’re calculating length * width inside the template literal. We can compute any JS code inside a template literal as long as it’s inside of ${}. Keep in mind that while you can do this, you probably shouldn’t, since it could quickly make your code less readable.

One last thing. Backticks can be used to create multi-line strings. It’s unlikely you’ll need this functionality much, but it’s still good to know. Here’s an example:

const multiLineString = `This is not
a good poem
about JavaScript.`

Check it out in the console. With template literals, our line breaks are preserved!