Using Template Literals

Single quotes and double quotes are used interchangeably in JavaScript, and both can only contain string literals. To embed the value of a variable or a result of an expression into a string, we traditionally used + to concatenate. But that can get verbose and noisy, as in the following example.

 const​ name1 = ​'Jack'​;
 const​ name2 = ​'Jill'​;
 
 console.log(​'Hello '​ + name1 + ​' and '​ + name2);

Code with multiple +s often gets unwieldy, unpleasant, hard to maintain, and boring to write. This is where template literals come in.

Template Literals

Template literals are strings with embedded expressions. The expressions may be a single variable, multiple variables with operators, a function ...

Get Rediscovering JavaScript now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.