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