JavaScriptReact

What Are Template Literals In Javascript And Why You Should Use Them

author image

Cloudaffle

Team

5th Jan, 2021   |   707 Words   |   5 Min Read

JavaScript has never had an elegant way of handling string until the launch of ES6. ES6 introduces something known as template literals, which enable JavaScript to handle multiple strings lines more efficiently and elegantly.

Syntax For Template Literals

Template literals do not intend to add additional functionality to the existing JavaScript stings but try to solve it in a new way. Hence, the introduction of the new syntax. Instead of using single quotes or double quotes, you can delimit strings using backticks. `.

// This is how strings were declared pre ES6
var earlierStrings = 'How strings were declared pre ES6';

// Declaring strings using template literals in ES6
let templateLiterals = How strings can be declared post ES6;

console.log(typeof earlierStrings); // "string"
console.log(typeof templateLiterals); // "string"

Template Literals Are An Answer To Multiline Strings In JavaScript

Multiline strings have always been a problem pre ES6 because the strings were declared using double quotes and single quotes. This was a problem because when you are declaring strings using double quotes or single quotes, the stings must completely be contained in a single line. Let’s look at how developers inserted multiple HTML lines in your JavaScript code to understand how template literals can be a boom.

var profile = '' +
    '    <div class="profile">\n' +
    '\n' +
    '        <div class="name">John Doe </div>\n'
    '\n' +
    '        <div class="designation">Web Developer</div>\n'
    '\n' +
    '    </div>\n';

You can certainly see the multiple concatenation lines and each string being contained to a single line single it has been declared using single quotes. This can be simplified using template literals using the following syntax.

let profile = `

<div class="profile">

<div class="name">John Doe </div>

<div class="designation">Web Developer</div>

</div>`.trim();

With template literals, it's super clean and easy. The trim function has been used to eliminate the space before the `div` tag and is not mandatory.

Populating data dynamically using template literal substitutions

Template literals are not just a fancy way of declaring strings in ES6. The real power of template literals can be understood using substitutions. Using substitutions, you can dynamically populate data within the strings declared using template literals, much like you would be able to do using a templating engine. Let's look at the following example:

let data = {

name: 'John Doe',

designation: 'Web Developer'

}

let profile = `

<div class="profile">

<div class="name">${date.name}</div>

<div class="designation">${data.designation}</div>

</div>`.trim();

Substitutions can be used to using the following syntax ${}. If you consider the above code example, you would realize that the substitutions can contain JavaScript expressions. Computing JavaScript expressions within substitutions make them really powerful and an inviting feature to ES6.

Tagged Template Literals

Template literals can have a tag preceding a declaration of the template literal itself. This tag acts like a normal javascript function that returns an array of literals and the function's substitutions. The literals and the substitutions can then be used within the function and manipulated to return the needed data, which would act as the final output of the template literal. Let’s first declare a template literal and then assign a tag to it.

let data = {

name: 'John',

age: '30'

}

let profile = `My name is ${data.name} and I am ${data.age} years old.`

console.log(profile);

// "My name is John and I am 30 years old."

This is a simple template literal. We can prefix the profile template literal with a new tag, which will act as a function name, and then we can use the literals and the substitutions within the function. Here is how you would do it.

function tagFunction(literals, ...substitutions){

console.log(literals);

// Returns: ["My name is ", " and I am ", " years old."]

console.log(substitutions);

// Returns: ["John", "30"]

let data = {

name: 'John',

age: '30'

}

let profile = tagFunction `My name is ${data.name} and I am ${data.age} years old.`

In the above example, you can see that the literals and substitutions are provided as parameters are available in an array within the function. You can use this information to manipulate the template literal and return a completely new string.

function tagFunction(literals, ...substitutions){

return `${literals [0]}Steve${literals [1]}25${literals [2]}`

}

let data = {

name: 'John',

age: '30'

}

let profile = tagFunction `My name is ${data.name} and I am ${data.age} years old.`

console.log(profile);

// "My name is Steve and I am 25 years old."

Using the tagFunction() in the above example, we have been able to override the string that is returned by the template literal completely. This is just a small example but should give you a fair idea of the functionality it adds to JavaScript strings.

What Are Your Thoughts About "What Are Template Literals In Javascript And Why You Should Use Them". Comment To Let Me Know.

I tried to cover all aspects of "What Are Template Literals In Javascript And Why You Should Use Them" and I would love to have a discussion and know your thoughts on the article. Feel free to post your feedback in the comments below and improve upon what we have over here. Happy Commenting 🙂 !