JS: Template Literals and More.!!

Rajesh Kumar
5 min readJun 15, 2020

This is a new ES6 feature added in the JavaScript.The first simple use of template literal is to enable you to solve the complex string problem in safer and clean way.

So right now most of you are thinking about many things like what does template literals means?What exactly it does?Does it only use to ease the string task ?But How? and many more…. So hold on we will went through each concept step by step and at the end of this all of you have clear understanding about Template Literals.Let’s Begin!!!

What does Template Literals means?

Template literals (formerly known as template strings) are string literals.

In computer science, a literal is a notation for representing a fixed value in source code.So simply it’s kind of notation and template refers to a pointed file/document like embedded expression.

So in simple words, A “template literal” is a new kind of string literal that can span multiple lines and interpolate expressions (include their results).

What exactly it does?

Traditionally, String is created using single quotes (‘) or double quotes (“) .And the strings have very limited functionality.

for example:
let str1= ‘Hello ’ ;
let str2= “World!” ;
let str = str1 + str2 ;
console.log(str) //Hello World!

At this point all things are looking good,but the actual problem will start appearing when you try to create the multi-line template and trying to concatenate expressions and variables and then add a quote and some special characters it’s become messy and complex.

So to rescue such problems ES6 came with new feature Template Literals.

As i have already mentioned above that, what is Template Literals.So let’s start with how to use template literals.

How to use Template Literals?

Template literal is created using the backtick (`) character.By using the backticks, you can freely use the single or double quotes in the template literal without escaping and without thinking to alternate between them.

let str = `First template literal`;
let anotherStr = `Let's start!!`;
console.log(str); //First template literal
console.log(anotherStr); //Let's start!!
console.log(str.length); //22
console.log(anotherStr.length); //13
console.log(type str); //string

Multi-line Strings

Traditionally in JS we use following mentioned techniques to create multi-line string by manually including the new line character (\n) in the string:

var msg = 'Traditional Multiline \n\
string';
console.log(msg);
//Traditional Multiline
//string

Note: black slash(\) used after \n is indicating the continuation of the string rather than new line.

Variable and Expression Substitution

As of now we have seen,template literal as a better version of just normal string.

But the actual big difference between a template literal and normal string is the substitution.

This substitution property of template literals gives the power of string interpolation.

**string interpolation** : The process of embedding variables and expressions in the string. The JavaScript engine will automatically replace these variables and expressions by their values.

To substitute the expression and variables in the string we used below syntax:

${var_name}

let’s see the example

//variable substitution
let country = 'India';
let name = 'John';
let msg =`Welcome to ${country} {name}`;
console.log(msg); //Welcome to India John
//Expression substitution
let a = 5;
let b = 6;
let sum = `Summation of ${a},${b}: ${a+b}`;
console.log(sum); //Summation of 5,6: 11

This is all about basic template literal.

WAIT…!!!!!! Have you thought that how these express manipulated and concatenated ?? 🌝

In the template literal `${expression}`, the text between the placeholders is passed to a function. The default function simply concatenates the template literal's parts into a single string.

Any time we see an expression preceding a template literal, we call the expression a tag and the template string a tagged template literal. In these instances, we call the tag expression (typically a function) with the processed template literal, which we can then manipulate before outputting the final string.

So to better understanding of these things we will see how Tagged Templates works!!

Tagged Templates

A tag templates perform the all the required manipulation and returns the result string.

So,Tagged template literals allow us to use a function to modify the output of a template literal.

SYNTAX:
tag_name template;
example: let greeting = tag`Hi`;
/*tag is the template tag that applies to the Hi template literal. The tag can be any function with the following signature*/function tag(literals, ...substitutions) { // return a string }
  1. The first argument contains an array of string literals.
  2. The subsequently processed arguments are the values of the substitution expressions.

After processing all the arguments, the function returns the manipulated string.

//Example without any explicit returnvar a = 5;
var b = 10;
function operation(strings, ...expVal) {
console.log("1." + strings[0] + ":");
console.log("2." + strings[1] + ":");
console.log("3." + strings[2] + ":");
console.log("__" + strings[3] + "__");
console.log(expVal[0]);
console.log(expVal[1]);
console.log(expVal[2]);
}
operation`Sum ${a + b}
Product ${a * b}
Division ${b / a}`;
//OUTPUT:
1.Sum :
2.
Product :
3.
Division :
----
10
26
4

In the above example we have used rest parameter(…).

Note:Rest parameter is an improved way to handle function parameter, allowing us to more easily handle various input as parameters in a function.

We will learn about this in more details in the article of Spread Operator.😃️

/*Example with explicit return*/
var a = 2;
var b = 8;
function operation(strings, ...values) {
let a = values[0];
let b = values[1];
return `Sum ${a + b}
Product ${a * b}
Division ${b / a}`;
}
let res = operation`Num1 ${a + 10}
Num2 ${b * 2}
Num3 ${b / a}`
console.log(res);//OUTPUT
Sum 28
Product 192
Division 1.3333333333333333

In the above example ,tag function manipulate the value accept expression values and ignore input string literals (i.e Num1,Num2, Num3) and append Sum ,Product & Division in that place and return the manipulated string.

“We can also nested the templates,which helps in few scenario to write clean and safe code.Let’s see.”

Nested Templates

Templates can be nested if it contains

  • multiple expression evaluation or
  • multiple condition checking

Instead of using else if ladder this is readable and gives ease to the developer.

let a = 2;
let b = 7;
let c = 5;
let nestedTemp = `value ${ (b>a && b>c) ? 'b is greater' :`${a>c ? 'a is greater' : 'c is greater'}` }`;
console.log(nestedTemp); // b is greater

I hope all points will have been clear.

If you have any queries feel free to ask in the comment section.Also give the feedback's so that i can improve.😉

--

--