Template Literals – Dynamic Strings Made Easy
With the introduction of ES6 (ECMAScript 2015), JavaScript has received numerous useful features. One of the most remarkable is the Template Literal (also called Template String). This new type of string notation significantly simplifies working with strings, especially when it comes to embedding variables or multi-line strings.
What are Template Literals?
Template Literals are string literals enclosed with backticks ` instead of single ' or double quotes ". They enable:
- Interpolation of expressions using
${expression}. - Multi-line strings without special characters or concatenations.
- Easy integration of variables and functions directly in the string.
Variable Interpolation
Before ES6, you had to insert variables into strings through concatenation:
const name = 'Anna';
const greeting = 'Hello, ' + name + '!';
console.log(greeting); // Output: Hello, Anna!
With Template Literals, this becomes much easier and more readable:
const name = 'Anna';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Anna!
Multi-line Strings
Creating multi-line strings used to be cumbersome and required special characters or concatenations:
const text = 'First line\n' +
'Second line\n' +
'Third line';
console.log(text);
With Template Literals, you can simply press Enter:
const text = `First line
Second line
Third line`;
console.log(text);
Expressions within Strings
You can use any JavaScript expressions within the ${} syntax:
const a = 5;
const b = 10;
console.log(`The sum of ${a} and ${b} is ${a + b}.`);
// Output: The sum of 5 and 10 is 15.
Functions can also be called:
function getUsername() {
return 'Max';
}
console.log(`Welcome, ${getUsername()}!`);
// Output: Welcome, Max!
Nested Template Literals
Template Literals can also be nested:
const isMember = true;
const greeting = `Good day, ${isMember ? 'valued member' : 'guest'}!`;
console.log(greeting);
// Output: Good day, valued member!
Tagged Templates
An advanced feature of Template Literals is Tagged Templates. Here, a function is placed before the Template Literal that processes the string:
function highlight(strings, ...values) {
return strings.reduce((result, string, i) => {
return `${result}${string}<strong>${values[i] || ''}</strong>`;
}, '');
}
const name = 'Lisa';
const age = 25;
const message = highlight`Name: ${name}, Age: ${age}`;
console.log(message);
// Output: Name: <strong>Lisa</strong>, Age: <strong>25</strong>
In this example, the highlight function formats the text by highlighting the inserted values.
Retrieving Raw String Data
With the String.raw property, you can retrieve the raw data of a Template Literal, which can be useful when you want to use backslashes or other special characters:
const filePath = String.raw`C:\Development\new_project`;
console.log(filePath);
// Output: C:\Development\new_project
Conclusion
Template Literals are a powerful tool for making strings in JavaScript more dynamic and readable. They not only simplify the embedding of variables and expressions but also enable easy creation of multi-line strings and the use of Tagged Templates for advanced string manipulations.
Try out Template Literals in your next project and experience how they can simplify your code!