The one of my favorite features in ES6 or ECMAScript 2015 is 'Template Literals'. Before I learn about 'Template Literals' in my Coding Boot-camp recently, I used to use string concatenation in JavaScript as following:
var user = { name: 'Gina', hobby: 'Traveling', }; console.log('Hi, I\'m ' + user.name + '! My hobby is "' + user.hobby + '".'); //Hi, I'm Gina! My hobby is "Traveling".
Now with template literals, I can write as following:
var user = { name: 'Gina', hobby: 'Traveling', }; console.log(`Hi, I'm ${user.name}! My hobby is "${user.hobby}".`); //Hi, I'm Gina! My hobby is "Traveling".
Both examples give the same result, but do you see how readable the second example is using the 'Template Literals'? When you are using string concatenation, you need to use the backslash(\) to escape special characters. Because of the duplicate usage of some of the characters, reading and understanding the text could be challenging. With Template Literals, you construct the string as you are writing a plain English sentence inside back-ticks(``). If you want to add variables, just use a dollar sign followed by curly brackets. You can even add a simple Javascript statement if it is necessary as following:
console.log(`Two times seven is ${2*7}.`); // Two times seven is 14.
In addition the line breaks got much easier with Template Literals.
With Template Literals: console.log(`Hi Gina, Good luck with your presentation today! -your friend`) //Hi Gina, Good luck with your presentation today! -your friend
Without Template Literals: console.log('Hi Gina, \n' + 'Good luck with your presentation today! \n' + '\t\t\t\t\t\t -your friend') //Hi Gina, Good luck with your presentation today! -your friend
Do you see how easy it is to read? With template literals, you create text as you write a note to your friend without using new line characters(\n) or tabs(\t). I have not encountered any issues with this feature so far and I really enjoy using it. If you have not tried it yet, you should definitely give a try...
Thanks for reading!
Top comments (0)