Peter Mekhaeil

JavaScript: Tagged Template Literals

Tag templates (or tag functions) parse template literals with a function:

function log(strings, ...args) {
  console.log(strings, args[0])
}

const person = "Peter";
log`My name is ${person}`;
// ['My name is ', ''] 'Peter'

First parameter is an array of strings, the following parameters are the variables that were passed in the expression. Think of them as substitutes. The string parts of the template have an index that matches the associated substitute that followed.

In the above example, ['My name is ', ''] was the string, Peter was the first substitute.

Tag templates can come useful in formatting strings:

function introduce(strings, ...args) {
let formattedString = '';

  strings.forEach((string, i) => {
    formattedString += string + (args[i] ? args[i].toUpperCase() : '');
  });

 return formattedString;
}

var person = "Peter";
introduce`My name is ${person}`
// 'My name is PETER'

Tagged Templates in the wild

const GET_DOGS = gql`
  query GetDogs {
    dogs {
      id
      breed
    }
  }
`;
const query = gql`
  {
    user(id: 5) {
      firstName
      lastName
    }
  }
`
const users = await sql`
  select
    name,
    age
  from users
`
const userId = 42
const result = await prisma.$queryRaw`SELECT * FROM User WHERE id = ${userId};`
const Button = styled.a`
  background: white;
  color: black;
`
const Input = tw.input`border hover:border-black`