JavaScript ยท Chapter 18 of 55

JavaScript Template Literals

Template literals use backtick characters (`` ` ``) instead of quotes, allowing you to embed expressions directly inside a string with `${expression}` syntax.

They also support multi-line strings without needing special escape characters, making them the preferred way to build dynamic text in modern JavaScript.

String interpolation

`${...}` can contain any JS expression, from a simple variable to a full calculation, and it gets converted to text automatically.

Multi-line strings

Unlike regular quoted strings, template literals can span multiple lines just by pressing Enter inside the backticks.

Example 1 (javascript)
let name = "Mia";
let age = 28;
console.log(`${name} is ${age} years old`);
Output
Mia is 28 years old

Variables are interpolated directly into the string.

Example 2 (javascript)
let msg = `Line one
Line two`;
console.log(msg);
Output
Line one
Line two

Template literals preserve line breaks naturally.

Key points

  • Template literals use backticks, not quotes.
  • `${expr}` embeds any JavaScript expression.
  • They support real multi-line strings.
  • They are the modern replacement for string concatenation.
๐Ÿ’ก Note: Template literals can also power 'tagged templates', an advanced feature used by libraries like styled-components.

๐Ÿ“ Quick Quiz

1. What character wraps a template literal?

2. How do you embed an expression in a template literal?

3. Can template literals span multiple lines?