javascripttemplate-literalsexpsuffixtagged-templates

Exp suffix appended to arguments/variable in Tagged Templates (JavaScript)


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates

This is the code from the link above:


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

function myTag(strings, personExp, ageExp) {
  let str0 = strings[0]; // "That "
  let str1 = strings[1]; // " is a "
  let str2 = strings[2]; // "."

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

  // We can even return a string built using a template literal
  return `${str0}${personExp}${str1}${ageStr}${str2}`;
}

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

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

There's no documentation related to the Exp suffix and how it is able to call variables with the correlated prefix. Anyone know where I can learn more or what is happening here?


Solution

  • The Exp suffix isn't special, it's just part of the variable name (it's an abbreviation of expression). From the MDN link you included:

    The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.

    Your template has 3 string chunks separated by expressions (an expression is ${} with something inside of it), and those chunks are "That ", " is a ", and "." So, the first argument, called strings in this case, would be ["That ", " is a ", "."]. There are two expressions, person and age, so they would be put into the subsequent arguments: the second argument would have the value of person, and the third would have to value of age. This is perhaps best illustrated in this snippet:

    function myTag(strings, a, b, c) {
        console.log(a, b, c);
    }
    
    myTag`foo ${1 + 1} bar ${2 + 2} baz ${3 + 3}` // logs 2 4 6