Explain Codes LogoExplain Codes Logo

How to interpolate variables in strings in JavaScript, without concatenation?

javascript
template-literals
string-interpolation
es6-features
Anton ShumikhinbyAnton Shumikhin·Aug 25, 2024
TLDR

Interpolate variables in JavaScript strings using template literals, which employ backticks (`\) and ${} as part of the syntax:

const user = 'Bob'; const message = `Hi, ${user}!`; // Returns "Hi, Bob!"

These literals provide a brevity miracle, wiping out manual concatenations and making strings more readable.

ES5 and Prior: The Concatenation Era

Before 2015, JavaScript didn't have template literals. The common approach to interpolating strings was using concatenation or sprintf.js:

// Ol' good concatenation way var user = 'Alice'; var message = 'Hi, ' + user + '!'; // sprintf.js: when you miss C in JS var message = sprintf("Hi, %s!", user);

Unique custom interpolation functions using replace() and regular expressions did make this process less of a chore:

function interpolate(template, values) { return template.replace(/\$\{(\w+)\}/g, function(_, key) { return values[key] || ''; }); } var template = "Hi, ${user}!"; var message = interpolate(template, { user: 'Alice' }); // "Hi, Alice!"

ES6 and Beyond: The Template Literals Era

Complex Expressions: More than Just Variables

Introduced in ES6, template literals allow executing more complex operations right within the strings:

const a = 5; const b = 10; // Math + String = Fun const sumMessage = `The sum of ${a} and ${b} is ${a + b}.`; // "The sum of 5 and 10 is 15."

Tagged Templates: Customize Your String Interpolation

Tagged templates handle string parsing via a function, influencing the interpolation logic and adding an extra flavor to template literals:

function highlight(strings, ...values) { return strings.reduce((acc, str, i) => `${acc}${str}<strong>${values[i] || ''}</strong>`, ''); } const user = 'Alice'; const messages = 5; // One string to inject them all const taggedMessage = highlight`Hello, ${user}! You have ${messages} new messages.`;

Legacy Support: Don't Forget Your Roots

Despite the luxurious simplicity of template literals, not all browsers support them. For wider compatibility, tools like Babel/Webpack transpile the ES6+ code to ES5, which works on older browsers that refuse to retire:

// Babel: When you need to time travel to ES5 var user = 'Alice'; var message = "Hello, " + user + "! You have " + messages + " messages.";

If you just want to perform simple logging, the good ol' console.log treats you with kind, basic string formatting, even on grumpy browsers like IE8:

// console.log: an old friend who always has your back. console.log("Hello, %s! You have %d messages.", user, messages);

The Swiss Army Knife: Multifunctional Template Literals

Multiline Strings: No Backslashes Needed

Working on multi-line strings? Template literals got you!

// Folds lines like an origami master const multiLineMessage = `This is a string that spans multiple lines without the need for a backslash!`;

Nested Template Literals: Because One Isn't Enough

For complex cases, nested template literals come in handy:

const item = 'cookies'; const count = 3; // A pluralizer in disguise const nestedMessage = `I bought ${count} ${ count === 1 ? item : `${item}s` }.`; // "I bought 3 cookies."

Working with Expressions: A Bit of Logic

Add spice to your strings with small operations or binary checks:

const hours = 9; // The string who knew too much const greeting = `Good ${hours < 12 ? 'morning' : 'afternoon'}, Alice!`;