Build Messages With Template Literals

At the end of the last lesson, your party message worked, but the code that built it was busy. Here’s the line that started it:

Language: JavaScript
let message = "Pizza night at " + host + "'s place!";

To read that line, you have to keep track of three pieces, two plus signs, and a space hiding at the end of "Pizza night at ". The message you actually care about is hard to see among all the quotes.

In this lesson, you’ll learn a second way to write strings that keeps the message in one piece and drops the values right into it. You’ll predict exactly what these strings produce, including calculations, dollar signs, and text over several lines. Then you’ll rewrite your message.js script from the last lesson and run it to check that the output stays the same.

Drop a Value Into a String With ${}

Start the Node REPL with node in the integrated terminal of your course folder. Give the host a name, and then type the message between two backticks (`). On many keyboards, the backtick key sits at the top left, below the Esc key:

Language: JavaScript
> const host = "Sam";
undefined
> `Pizza night at ${host}'s place!`
"Pizza night at Sam's place!"

A string written between backticks is called a template literal. It works like the strings you already know, with one extra power.

Anywhere inside it, you can write ${, an expression, and }. This spot is called a placeholder. When JavaScript builds the string, it works out the expression inside the placeholder and puts the result into the text at that spot.

Compare this line with the + version at the top of the lesson. The text reads in one go, exactly as it’ll come out, and ${host} marks the one part that changes. The space after at sits visibly in place, so you don’t have to hunt for it at the edge of a quoted piece.

There’s a bonus, too. The apostrophe in Sam's doesn’t need an escape or a different kind of quote, because only a backtick ends a template literal. The REPL still shows the result in quotes, since what you built is an ordinary string. Backticks are just another way to write one.

That also means you don’t need backticks for every string. Plain text without any placeholders stays in double quotes, as before. Reach for backticks when a value goes into the text.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.