How to interpolate variables in strings in JavaScript, without concatenation?
Interpolate variables in JavaScript strings using template literals, which employ backticks (`\
) and ${} as part of the syntax:
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:
Unique custom interpolation functions using replace()
and regular expressions did make this process less of a chore:
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:
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:
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:
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:
The Swiss Army Knife: Multifunctional Template Literals
Multiline Strings: No Backslashes Needed
Working on multi-line strings? Template literals got you!
Nested Template Literals: Because One Isn't Enough
For complex cases, nested template literals come in handy:
Working with Expressions: A Bit of Logic
Add spice to your strings with small operations or binary checks:
Was this article helpful?