I recently learned that ES6 allows to make function calls without parentheses when using a template literal as a parameter. E.g.
showstring`Hello World`;
After reading a few articles on this functionality, however, I have come away with scant information as to the logic behind how JS handles these calls.
After playing around with some permutations of my code, I am still struggling to piece together the pattern of how a template literal is broken down inside the function when one calls it that way.
const showstring = (str) => {
console.log(str);
}
showstring`Hello World`;
What happens in the above code is straightforward, the string literal is received as an array where the first and only element is the string.
Where it gets a bit confusing is once I start using expressions inside the template. E.g.
const showstring = (str, ...values) => {
console.log(str);
console.log(values)
}
const name = 'John'
showstring`Hello World ${name} ${name} ${1 + 2} and more`;
So it looks like the ...values
part destructures all the expressions. But why, then, does the str
array have empty strings in those spots?
I just don't fully grasp the pattern it follows here. Can someone explain this feature? Or perhaps point me to a good article?