Learning Template Literals
Template literals are a new form of string that was introduced in ECMAScript 6. They are enclosed by the backtick symbol (``
) instead of the usual single or double quotes. Template literals allow you to embed expressions in the string that are evaluated at runtime. Thus, we can easily create dynamic strings from variables and variable expressions. These expressions are denoted with the dollar sign and curly braces (${ expression }
). The template literal syntax is shown in the following code:
const example = "pretty"; console.log( `Template literals are ${ example } useful!!!` ); // Expected output: Template literals are pretty useful!!!
Snippet 1.22: Template literal basic syntax
Template literals are escaped like other strings in JavaScript. To escape a template literal, simply use a backslash (\
) character. For example, the following equalities evaluate to true: `\`` === "`",`\t` === "\t"
, and `\n\r` === "\n...