So here we are today to further analyze the new features of ES6. What we’re going to talk about today are Template Literals.

Let’s start with a definition :

Template literals are a new, easier way to improve our code readability when working with Strings 

 

Let’s all forget about those bad old days when we had to write long, tedious Strings concatenations and let’s all enjoy this new feature.

A couple examples

The new syntax for this feature is no more the  ‘single quote’ or  "double quote" but instead, we will use the  `backtick` character:

var singleQuote = 'hello world';
var doubleQuote = "hello world";

var templateLiteral = `Hello world`; // new template literals string

 

But please don’t get confused, template literals that make use of the  `backtick` character are still strings, but we can use them to perform common strings operations in more redable ways!

String concatenation

One of the most obvious way in which template literals can improve our code is when talking about concatenating strings, consider the example

var name = 'piero';
var surname = 'borrelli';
console.log('Hi, I\'m ' + name + ' ' + surname);

 

I don’t know about you but simply writing that string inside the console log gets me stressed. First I have to think about the escape sequences for the apostrophe and second, I have to interrupt the stream of characters to print out the values I have stored. But see how we can improve this code with template literals :

 

var name = 'piero';
var surname = 'borrelli';
console.log(`Hi I'm ${name} ${surname}`);

 

See! No more escape sequences, no more boring typing of your variables. With template literals we can avoid that.

Notice the ${expression} syntax, this syntax is used to print values inside our strings. And we are not obliged to use it with variables only! we can use it with any valid expression we want.

var price = 100;
var taxes = 22;
console.log(`The final price for the dress is ${price * taxes}`);

Line Breaks

Another useful example where we can use template literals is with Line Breaks. Consider the old way :

var loveLetter = "My love, \n" +
"life is hard in the office, \n"
+ "the code didn't compile and now the boss...";

 

Boring right? Let’s go with template literals :

var loveLetter = `My love,
life is hard in the office,
+ the code didn't compile and now the boss...`;

 

A lot better! Keep in mind that this expression is possible because with template literals all new line characters, tabs, spaces, etc. inserted in the source become a part of the string.
And that was it for today. 
Stay tuned for more useful articles and tutorials
Happy learning!

 

 

 

 

 

 

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here