Template Literals

Embed variables and expressions directly inside strings.

Syntax`Hello, ${name}!`

Template literals use backticks ` instead of quotes. They let you insert variables and expressions with ${ }, and they can span multiple lines.

Why they are better

No more messy + concatenation — just drop values right into the text.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Build a personalised email body that interpolates the user's name, order ID, and total.
  • Construct a multi-line SQL query string cleanly without string concatenation.
  • Embed a conditional expression inside a notification message to choose singular vs plural wording.

More examples

Embed expressions in a string

Interpolates a name, count, and formatted number directly inside a template literal.

Example · js
const user = "Alice";
const items = 3;
const total = 59.97;
console.log(`Hi ${user}, your ${items} items total $${total.toFixed(2)}.`);

Multi-line SQL query

Uses a template literal to write a multi-line SQL query with natural indentation and no concatenation.

Example · js
const query = `
  SELECT id, name, email
  FROM users
  WHERE active = true
  ORDER BY name ASC
`;
console.log(query);

Inline conditional in template

Embeds a ternary expression inside a template literal to choose the correct plural form.

Example · js
const count = 1;
const msg = `You have ${count} new ${count === 1 ? "notification" : "notifications"}.`;
console.log(msg); // "You have 1 new notification."

Discussion

  • Be the first to comment on this lesson.