Skip to content

Instantly share code, notes, and snippets.

@rohit1101
Created April 5, 2022 13:22
Show Gist options
  • Save rohit1101/9f08f41ca740f08e110436e68e5bdb90 to your computer and use it in GitHub Desktop.
Save rohit1101/9f08f41ca740f08e110436e68e5bdb90 to your computer and use it in GitHub Desktop.
Blog - 01

What are tagged template literals ?

We are already aware of template literal as shown below:

const name="Groot"
console.log(`I am ${name}`)

When we use template literal any JavaScript expression is valid within the curly braces {}.

Now, let us learn about tagged template literal.

function blackBox(strings,name) {
    console.log(strings, name)
}

const name='Groot'
blackBox`I am ${name}!` 

The output of the above code snippet is:

Array ["I am ","!"] Groot

The first argument of blackBox function is an array of strings and the second argument is just valid JavaScript expression.

But we can have n number of template interpolation, for example:

const blackBox = (strings,...args) => {
    console.log(strings, args) 
}

const firstName="Rohit" 
const lastName="S" 
const age=200

blackBox`I am ${firstName}, ${lastName} and ${age}.`

The output of the above code snippet is:

Array(4) [ "I am ", ", ", " and ", "." ]
Array(3) [ "Rohit", "S", 200 ]

Pro-tip: Tagged templates works well with ES6 arrow function declaration and also supports

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment