Template literals were introduced as part of ECMAScript 2015 (ES6) and provide a more flexible way of working with strings.
They make it easier to insert variables into strings and also allow strings to span multiple lines without the need for special characters.
Template literals are commonly used throughout modern JavaScript and are particularly popular in frameworks such as React.
What template literals are
A template literal is a string enclosed using backtick characters
(`) rather than single or double quotes.
Consider the following:
const message = `Hello world`;
This produces exactly the same result as a normal string declaration.
String concatenation
Before template literals were introduced, strings and variables were often
combined using the concatenation operator (+).
Consider the following:
const name = "John"; const message = "Hello " + name;
This technique is still valid, but template literals provide a cleaner solution.
Basic template literals
Variables can be inserted into template literals using the
${...} syntax.
The previous example can therefore be written as:
const name = "John"; const message = `Hello ${name}`;
The value of message will be:
Hello John
Embedding variables
Multiple variables can be embedded within the same template literal.
Consider the following:
const first_name = "John"; const last_name = "Smith"; const full_name = `${first_name} ${last_name}`;
The value of full_name will be:
John Smith
Embedding expressions
Template literals are not limited to variables. JavaScript expressions may
also be evaluated inside the ${...} syntax.
Consider the following:
const message = `2 + 2 = ${2 + 2}`;
The result will be:
2 + 2 = 4
This can be particularly useful when constructing dynamic messages.
Multi-line strings
Traditional strings cannot span multiple lines without special characters.
Consider the following:
const text = ` This is line one. This is line two. This is line three. `;
Everything between the opening and closing backticks becomes part of the string.
This makes template literals particularly useful when constructing larger blocks of text.
When to use template literals
Template literals are generally easier to read than string concatenation, especially when multiple variables are involved.
They should be preferred when constructing dynamic strings and when working with multi-line text.
Since template literals appear frequently throughout modern JavaScript, React and Node.js applications, understanding them is an important part of learning modern JavaScript.
