Getting Started with Modern JavaScript — Template Literals
Introduced in 2015 with ECMAScript6, template literals let us dynamically construct strings of text and embedded expressions, even multi-line strings of text, in a more elegant way than concatenation.
The syntax is not much different from the old one at first glance:
const newWay = `is cool`;
Can you spot the difference? Instead of single '’
or double "”
quotes we use backticks ``
.
String Interpolation
In ES5 you had string concatenation:
const name = 'Jack';
const old = 'My name is '+ name + '.';
Using +
for both addition and concatenation can be confusing and even lead to unexpected bugs:
Template literals provide an easy way to interpolate variables and expressions into strings. The curly braces accept any valid JavaScript expression inside the ${}
: