JavaScript:
Interpolating a string

How to:

In JavaScript, string interpolation is often done using template literals. Here’s how you can do it:

const name = 'Alice';
const message = `Hello, ${name}! How are you today?`;
console.log(message); // Outputs: Hello, Alice! How are you today?

You can also perform operations within placeholders:

const a = 10;
const b = 5;
console.log(`Ten times five is ${a * b}.`); // Outputs: Ten times five is 50.

Deep Dive

Historically, string interpolation wasn’t as straightforward in JavaScript. Before ES6 (ECMAScript 2015), concatenation was commonly done using the + operator:

var name = 'Bob';
var message = 'Hello, ' + name + '! How are you today?';

With the introduction of ES6, template literals (between backticks ` `) came along, bringing an easier syntax with the ${} placeholders.

Alternatives to string interpolation include string concatenation with the + operator and concat() method, or using sprintf-like functions from third-party libraries.

The performance of template literals is generally on par with these older methods. However, readability and the ability to include expressions (like ${a * b}) within strings make template literals a strong choice for developers.

See Also