What is the purpose of template literals (backticks) following a variable definition in ES6?

  • A+

In GraphQL you can write something like this to define a query:

const USER_QUERY = gql`   {     user(id: 2) {       name     }   } ` 

In styled components you can define a styled component like this:

const Button = styled.button`     background-color: papayawhip; ` 

What is this syntax? I know with template literals you can sub in variables with this syntax: ${foo} but I have never seen this used. Any guidance would be appreciated.


Template literals have an additional feature called tagged templates. That's what the prefix before the opening backtick is. The prefix is actually the name of a function - the function is passed the constant parts of the template strings and the interpolated values (stuff in the ${} sections) and can process the resulting string into whatever it wants (although generally another string, doesn't have to be).

See this page on MDN for more details on how tagged templates work.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: