When you compose a string from multiple other strings and values in JavaScript, things can get ugly.
function logError(error, date) {
console.log('Error: ' + error.message + ', ' + date.toString());
}
logError(new Error('Something went wrong!'), new Date());
This is already not pleasant with two values. It gets even worse as you introduce more.
ECMAScript 2015 introduced template literals, which can help make this sort of thing a bit more readable:
function logErrorTemplated(error, date) {
console.log(`Error: ${error.message}, ${date.toString()}`);
}
logErrorTemplated(new Error('Something went wrong!'), new Date());
Pretty straightforward: A template literal uses backticks instead of quotes, and you can embed expressions into it using ${}
.
You can also use newline characters in a template literal without having to insert \n
.
console.log('Line one\nLine two');
…can become…
console.log(`Line one
Line two`);
…or if you prefer…
console.log(`Line one\nLine two`);
All three of these produce the same output.