DEV Community

buginit
buginit

Posted on

Things you need to know about Tagged Template Literal in JavaScript

In simple words: JavaScript Tagged template literal is a function call that uses a template literal to get its arguments.
Here is a tagged function example:

greet`I'm ${name}. I'm ${age} years old.`;

Don't get yourself confused, In the above example, greet is a function that takes three arguments

  1. The first parameter is an array containing all of the text from our template literal.
  2. The 2nd to infinity parameters in our function are the variables to be inserted into our tag function. Here I'll show you the greet function from inside in detail.
// creating name and age variable 
var name = 'buginit';
var age = 1; 

// creating a greet function
function greet(strings, name, age) {
  var str0 = strings[0]; // "I'm"
  var str1 = strings[1]; // ". I'm"
  var str2 = strings[2]; // "years old."
  console.log(name) // buginit
  console.log(age) // 1
}

// calling greet function here and passing 
// name and age variable that we created above
greet`I'm ${name}. I'm ${age} years old.`;


Explanation: First we created two variables called name and age.

Then we defined the greet function,

And then called the greet function with those two variables and some strings around using Tagged Template Literals. So the greet function will receive all the strings as an array in the first argument and those variables in the rest of the arguments as shown in the above example please read comments inside example.

I hope you got the picture in your mind.

Wanna see more example and real-word examples check this out A Complete Guide: Tagged Template Literal In JavaScript


Originally published at buginit.com on October 9, 2019. For latest updates follow buginit

Top comments (0)