Before ES6(ECMAScript 2015), we have used single quotes(‘…’) and double quotes(“…”) to wrap string literals. A simple example is,

var msg = "Hello, I'm Joe and my favorite color is purple";

There were limitations when we had to concatenate multiple strings and the string literal has dynamic values. The readability of these concatenations used to be a challenge as well.

var frag1 = "Hello, I'm";
var val1= "Joe";
var frag2 = "and my favorite color is";
var val2 = "purple";

var msg = frag1 + ' ' + val1 + ' ' + frag2 + ' ' + val2;

Do you see another problem? If someone only reading the line where the concatenation takes place, he/she doesn’t have much idea of the resultant string.

With ES6 we have got template literals which are string literals that allow embedding expressions. Template literals are enclosed by the backtick ( ) characters instead of single or double-quotes.

Template literals can contain placeholders that are specified by the dollar sign($) and curly braces(${expression}). The above example can be written with template literals as,

const name = 'Joe';
const color = 'purple';

const message = `Hello, I'm ${name} and my favorite color is ${color}`;
console.log(message);

Output,

Hello, I'm Joe and my favorite color is purple

This is much better and favorable for developers to use.

What is the Tagged Template Literal?

A Tagged Template Literal is usually a function that precedes a template literal to help you in manipulating the output. It’s fine if you find it confusing. We will understand it in a few simple steps.

Let us take an example of this template literal again,

`Hello, I'm ${name} and my favorite color is ${color}`

We want to manipulate the output such that, it returns a string like the below when we pass the name as, Joe and color as, green.

#javascript #es6 #programming #js #ecmascript-6 #web-development #codenewbies #beginners

What Is Tagged Template Literal In Javascript
2.00 GEEK