CodeBlanks Logo Icon CodeBlanks

Template literals

Learn to build strings with template literals.

Template literals

A template literal is a special string written between backtick (`) characters. You can embed variables and expressions inside it.

Example: `Hello, ${name}!`. Here ${name} injects the value of the name variable into the string. This is shorter than writing 'Hello, ' + name + '!'.

Template literals also allow newlines; you do not need to write \n.

Injecting expressions with ${}

You can inject not only variables but also expressions inside a template literal. Any JavaScript expression can go inside ${...}.

Example: `Total: ${price + tax}`. Here price + tax is computed and the result is injected into the string. This is shorter than computing it separately.

You can even call a function: `Hello, ${greet(name)}`. The expression inside is evaluated first.

Practice Print with a template literal

Declare const name = 'Alex' and const age = 28. Use a template literal to print Hello, ${name}! Age: ${age} with console.log.

Starter code

index.js
const name = "Alex";
const age = 28;
// Use ${} inside backticks with name and age

Sample solution

index.js
const name = "Alex";
const age = 28;
console.log(`Hello, ${name}! Age: ${age}`);

Expected output

Hello, Alex! Age: 28

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the template concepts

Term Meaning
`...` Template literal
${...} Variable injection
${name} The name variable
console.log Print output

2 How is a template literal written?

  • With 'single quotes'
  • With "double quotes"
  • With `backticks` Correct answer
  • With [square brackets]

Explanation: Template literals use backticks.

3 Template literal syntax

Question
console.log(`Hello, ____`);
Answer
console.log(`Hello, ${name}`);

Explanation: ${name} injects a variable inside a template literal.

All lessons in Beginner