Codiqo

Learn JavaScript · lesson 5 of 60 · about 6 minutes

Template Literals

Stop fighting with + and spaces: drop values straight into your page's text with backticks and ${}.

What you'll learn

  • Join strings with +
  • Write template literals with backticks
  • Insert expressions with ${}

Too many plus signs

Sam's page should say *Sam has been coding for 3 days.* With + you glue the pieces end to end, and every space has to be typed inside a string by hand. Miss one and the words run together.

The same sentence twice: spot the missing spaces

const owner = "Sam";
const days = 3;
console.log(owner + " has been coding for " + days + " days.");
console.log(owner + " has been coding for" + days + "days.");

Output

Sam has been coding for 3 days.
Sam has been coding for3days.

Template literals

Write the text between backticks instead of quotes (the backtick key is usually left of 1). That's a template literal: anything inside ${ } is worked out and dropped into the text, right where it sits. The spaces are just part of the sentence, so you can see them.

One template literal, and the sentence is on the page

const owner = "Sam";
const days = 3;
document.querySelector("#about").textContent = `${owner} has been coding for ${days} days.`;

Maths works inside ${} too

const days = 3;
const lines = 120;
console.log(`Lines a day: ${lines / days}`);

Output

Lines a day: 40

Tip

Only backticks do this. In single or double quotes, ${days} is just six ordinary characters.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.