Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript String Interpolation

String interpolation inserts values directly into a string using ${}.

It is cleaner than concatenation for complex strings.

Why We Need It

UI strings often combine text and data. Interpolation keeps them readable.

It reduces mistakes compared to multiple + operators.

Syntax

`Hello ${name}`
`Total: ${price + tax}`

Basic Example

1. Basic interpolation

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

console.log(msg);

Insert a variable into a string.

Real World Example

2. Expressions

const price = 100;
const tax = 0.18;
const total = `Total: ${price + price * tax}`;

console.log(total);

Use expressions inside ${}.

Multiple Use Cases

Insert Values

String interpolation inserts variables or expressions into a string.

In JavaScript, interpolation is done with template literals.

Cleaner Than Concatenation

Interpolation avoids + concatenation and keeps strings readable.

It reduces bugs in long strings and UI templates.

Expressions Work Too

You can embed any expression inside ${}.

This includes math, function calls, or ternaries.

More Examples

3. Conditional

const isMember = true;
const label = `Price: ${isMember ? 'Member' : 'Standard'}`;

console.log(label);

Ternaries work inside interpolation.

4. Function call

function format(n) { return n.toFixed(2); }
const value = `Amount: ${format(12.3)}`;

console.log(value);

Call functions inside templates.

Comparison

Without

const msg = "Hello " + name + "!";

With

const msg = `Hello ${name}!`;

Common Mistakes and Fixes

Using quotes instead of backticks

Interpolation only works with backticks.

Forgetting ${}

Use ${expression}, not {expression}.

Overcomplicated templates

Move complex logic into variables or functions.

Interview Questions

What syntax enables interpolation?

Template literals with backticks.

Can you use expressions inside?

Yes, any expression inside ${}.

What if you need complex logic?

Move it into a variable or function first.

Practice Problem

Practice: Build a message that shows username and item count.

const user = 'Ava';
const count = 3;
// TODO: create message

One Possible Solution

const user = 'Ava';
const count = 3;
const msg = `User ${user} has ${count} items`;
console.log(msg);

Frequently Asked Questions

How do you interpolate in JavaScript?

Use template literals with ${} expressions.

Can I use expressions?

Yes, any valid expression works.

Is interpolation faster than concatenation?

Performance is similar; choose readability.

Try It Yourself

Try different expressions inside ${}.