What are the purposes of "tags" in template strings with ES2015?

89 Views Asked by At

I saw that tags can be used like this, and you may need it for "security" reasons, anyway, here is the example I got :

let person = 'Mike';
let age = 28;

function myTag(strings, personExp, ageExp) {

  let str0 = strings[0]; // "that "
  let str1 = strings[1]; // " is a "
  let ageStr;

  if (ageExp > 99) {
    ageStr = 'centenarian';
  } else {
    ageStr = 'youngster';
  }

  return str0 + personExp + str1 + ageStr;
}

let output = myTag `that ${ person } is a ${ age }`;

console.log(output); // that Mike is a youngster

But what is the point of "tagging" some strings, you do not even need that to get the result of this example, a simple function can do the job, could you give me an other example and some explanation with it ?

1

There are 1 best solutions below

0
On BEST ANSWER

According to the community answers here and the documentation :

  1. https://codeburst.io/javascript-es6-tagged-template-literals-a45c26e54761
  2. https://developers.google.com/web/updates/2015/01/ES6-Template-Strings

the purposes are that you do not have to pass each and every variable separately:

myTag`that ${ person } is a ${ age };`

and not

myTag('that ', person, ' is a ', age);

and inside the tag function "myTag" you can access each part of the string separated by a placeholder like this one ${placecholder} with its index : string[0] // that, string[1] // person, etc.

It is some utility tool that allows you to make easy replacement of placeholders.