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

Written by manik | Published 2020/03/14
Tech Story Tags: javascript | javascript-fundamentals | understanding-javascript | javascript-development | web-development | programming | nodejs | tutorial | web-monetization

TLDR ES6 introduces something know as template literals, which enable JavaScript to handle multiples lines of strings more efficiently and elegantly. Instead of using single quotes or double quotes, you can delimit strings using backticks (`) This is how strings were declared pre ES6 using double quotes or single quotes. Using substitutions you can dynamically populate data within the strings declared using template literal substitutions. Substitutions can be used to compute JavaScript expressions within them. This makes them powerful and an inviting feature to ES6.via the TL;DR App

JavaScript has never had an elegant way of handling string until the launch of ES6. ES6 introduces something know as template literals, which enable JavaScript to handle multiples lines of strings 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 the problem 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 used to insert multiple lines of HTML 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 lines of concatenation 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 get rid of the empty 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 the 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 within them. Having the ability to compute JavaScript expressions within substitutions makes 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 as well as the substitutions within the function itself. The literals and the substitutions can then be used within the function and manipulated to return the data that is needed and that would act as the final output of the template literal. Lets 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. Now 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 the form of an array within the function. You can use this information to manipulate the data within 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.

Written by manik | Out Of The Box Thinker, Love To Write JavaScript. "🍺 🍻 gulp watch"
Published by HackerNoon on 2020/03/14