Template Literals: The Easy Way to Build Strings

Grade 2, page 3 of 13. A one-minute read.

In Grade 1, we built messages by gluing strings and variables together with +:

JavaScript
const name = "Lucas";
const age = 16;
console.log("My name is " + name + " and I am " + age + " years old.");

It prints

My name is Lucas and I am 16 years old.

It works, but all those + signs and quotes are a pain to type, and it's really easy to forget a space. There's a better way.

Strings made with backticks (`) are called template literals, and they have a superpower: you can drop variables straight into them using ${ }.

JavaScript
const name = "Lucas";
const age = 16;
console.log(`My name is ${name} and I am ${age} years old.`);

It prints

My name is Lucas and I am 16 years old.

So much cleaner! Whatever you put inside ${ } gets worked out and inserted into the string. It doesn't have to be just a variable. It can be any JavaScript expression, like some math:

JavaScript
const price = 25;
const quantity = 4;
console.log(`${quantity} items cost $${price * quantity} in total.`);
console.log(`Two plus two is ${2 + 2}. Quick maths.`);

It prints

4 items cost $100 in total.
Two plus two is 4. Quick maths.

Template literals can also span multiple lines, no \n required:

JavaScript
const poem = `Roses are red,
Violets are blue,
I learned template literals,
And now so can you.`;

console.log(poem);

It prints

Roses are red,
Violets are blue,
I learned template literals,
And now so can you.
TipWhere's the backtick key?

On most keyboards, the backtick ` is in the top-left corner, just below Esc and to the left of 1. It shares a key with the tilde ~. It's easy to confuse with the single quote ', but they're different characters!

From now on, we'll use template literals whenever we need to mix variables into text. They're the modern, friendly way.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning