Skip to content

Step 1 of 5 · Reading · ~3 min

Learn

Strings

Template Literals

By the end of this lesson you can build any line of text, or several lines, from variables and calculations in a single readable expression.

The problem with +

Building a sentence with + means closing and reopening quotes at every seam:

javascript

Every seam is a place to forget a space. A template literal keeps the sentence whole. Use backticks (`) instead of quotes and put values inside ${...}:

javascript

What you type is the shape of what is printed, with the ${...} holes filled in.

Backticks, not quotes

Interpolation happens only inside backticks. In ordinary quotes ${plan} is plain text:

javascript

If your output contains a literal ${, you used the wrong quote character. The backtick key is usually at the top-left of the keyboard, below Esc.

A hole holds any expression

Anything that produces a value can go in the braces: arithmetic, method calls and comparisons.

javascript

toFixed(n) returns a string with exactly n decimals, handy for prices. Keep each hole short; if it needs a paragraph of logic, calculate it into a const first and put the name in the hole.

Line breaks are kept

A real line break inside backticks becomes a line break in the string, so you do not need \n:

javascript

Everything between the backticks is kept, including leading spaces. If you indent the continuation lines to line up with your code, the indentation ends up in the output.

Dollar signs and literal backticks

A $ only starts a hole when a { follows it. A $ on its own is ordinary text, so a price is written with the dollar sign first and the hole after it:

javascript

To print a backtick inside a template, escape it: `use \`code\` here`. To print the characters ${, write \${.

Common mistakes

  • Using ' or " and printing ${name} literally.
  • Putting a + or a quote inside the braces out of habit: ${"a" + b} works but adds noise. Put values in directly.
  • Indenting the lines of a multi-line template, which adds spaces to the output the grader will not forgive.
  • Writing $ and { together in front of a price by accident, swallowing the dollar sign. Remember the pattern: dollar sign, then ${value}.

Your exercise

Print a three-line receipt from one template literal. The starter reads the item, the unit price and the quantity; you decide what goes in each hole and how the lines are laid out.

Up nextConditionals: if, else if, elseControl Flow

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…