Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Template Literals

Template literals use backticks and allow interpolation with ${}.

They make string formatting cleaner and more readable.

Why We Need It

String concatenation can get messy with multiple variables.

Template literals keep formatting clear and maintainable.

Syntax

`Hello ${name}`
`Line1
Line2`

Basic Example

1. Basic template

const name = 'Ava';
const msg = `Hello ${name}`;

console.log(msg);

Interpolate variables with ${}.

Real World Example

2. Multi-line

const text = `Line one
Line two`;

console.log(text);

Template literals preserve line breaks.

Multiple Use Cases

Backtick Strings

Template literals use backticks (`) instead of quotes.

They make multi-line strings and interpolation easy.

Interpolation

Use ${} to insert variables or expressions into strings.

This is cleaner than string concatenation.

Tagged Templates

Template literals can be tagged to process strings in custom ways.

This is advanced but useful for localization or formatting.

More Examples

3. Expressions

const a = 2;
const b = 3;
const sum = `Total: ${a + b}`;

console.log(sum);

You can place any expression inside ${}.

4. Tagged template

function tag(strings, value) {
  return strings[0] + value.toUpperCase();
}

const result = tag`Hi ${'ava'}`;
console.log(result);

Tagged templates give you control over formatting.

Comparison

Without

const msg = "Hello " + name + ", you have " + count + " items";

With

const msg = `Hello ${name}, you have ${count} items`;

Common Mistakes and Fixes

Using quotes instead of backticks

Interpolation only works in backtick strings.

Forgetting braces

Use ${expression}, not $expression.

Overusing tagged templates

Use tags only when you need custom formatting.

Interview Questions

What symbol is used for template literals?

Backticks (`).

How do you interpolate variables?

Use ${variable} inside the template literal.

What is a tagged template?

A function that processes a template literal.

Practice Problem

Practice: Create a template literal that shows a user's name and age.

const name = 'Ava';
const age = 22;
// TODO: create message

One Possible Solution

const name = 'Ava';
const age = 22;
const msg = `Name: ${name}, Age: ${age}`;
console.log(msg);

Frequently Asked Questions

How do template literals differ from strings?

They allow interpolation and multi-line content.

Can I use expressions inside?

Yes, any expression inside ${} is allowed.

Are template literals slower?

Performance is similar; choose readability.

Try It Yourself

Try interpolating different values.