CodeBlanks Logo Icon CodeBlanks

Template literals

JavaScript course · Beginner · Lesson 33/133

Learn template literals with backticks and using expressions inside ${}.

Template literals with backticks

In JavaScript a template literal is a string wrapped in backticks (`). This key usually sits to the left of 1 on the keyboard.

The power of a template literal is that you can put an expression inside ${}. Example: `Hello ${name}`. The expression inside the curly braces is evaluated and embedded into the string.

You can break lines inside backticks; the string becomes multi line. This reads better than + concatenation.

Embedding expressions with ${}

Inside ${} you can put any expression, not only a variable: arithmetic, a method call, even another template literal.

Examples: `Total: ${a + b}`, `Length: ${word.length}`. The expression is evaluated first and then embedded into the string.

Inside backticks you can press Enter directly; the string becomes multi line. You no longer need to write \n for a new line.

Exercise Build a message with a template literal

Declare product as "Pen" and price as the number 12.5. Build message as a template literal that uses both ${product} and ${price}. Log message with console.log.

Show example solution
const product = "Pen";
const price = 12.5;
const message = `${product} costs ${price} lira`;
console.log(message);

Test yourself

  1. Which one is a template literal?

    • "Hello"
    • 'Hello'
    • [Hello]
    • `Hello`
    Show answer

    `Hello` — Correct. A string wrapped in backticks (`) is a template literal.

  2. Embed the expression in a template literal

    const name = "Ayşe"; const greeting = `Merhaba ____`;
    Show answer
    const name = "Ayşe"; const greeting = `Merhaba ${name}`;
  3. Match each syntax to its meaning

    `str`
    Template literal
    ${expr}
    Expression embedding
    'str'
    Single quoted string
    "str"
    Double quoted string
  4. What does `${3 + 4}` give?

    console.log(`${3 + 4}`);
    • "3 + 4"
    • "7"
    • "${3 + 4}"
    • 7
    Show answer

    "7" — Correct. The expression inside ${} is evaluated first (3 + 4 = 7) and then embedded.

All lessons in Beginner