Template literals

I have to print a message with values of, say, two variables interpolated or inserted in it. I am talking about JavaScript here. What I do is start single or double quotes, write some part of my message string, close the quotes, insert the variable, start quotes for remaining part of the message and keep going. If the number of variables is more, it’s a pain in the ass. Sometimes one tends up forgetting closing quotes somewhere and then check out the point of error. This can be illustrated as:

var person = {name: "Kamalpreet", age: "24"};
console.log("My name is " + person.name + " and I am " + person.age + " years old.");

This has been simplified by EcmaScript6 (ES6). The third type of quotes, the back-tick ones are used to escape all this fuss. The back-tick quote is used along with $() to contain the variable syntax. An illustration for the same example above is shown below:

console.log(`My name is $(person.name) and I am $(person.age) years old`);

Same output is shown by using both the methods. Latter one is simple and a part of ES6. This is called template literals or template strings. Another point that differentiates template literals is the definition of the string can be spanned across multiple lines without use of linefeed character. For an instance,

console.log(`Hello, my name is 
${person.name} and I am ${person.age}
years old`);

Prior to the introduction of template strings, this would have been done as:

console.log("Hello, my name is " + \
person.name + " and I am " + person.age + \
" years old");

These were few simplifications towards cleaner code introduced in ES6. There are few more which I will write about as I learn.

Leave a Reply

Follow

Get notified with the latest posts

Plugin Supporter WordPress Post Navigation
%d bloggers like this: