Came across this javascript riddle on Twitter today: https://twitter.com/bradleymeck/status/890795540123865088
// #js
const a = f => f``;
const b = f => f``;
console.log(a(_ => _) === b(_ => _));
// what do you think this will/may print
At first glance it actually seems to make some decent sense. a is a function that takes some input f and then does f``. What f`` is a complete mystery to me so I tossed it into the console and received this input.
(()=>{console.log('hi')})``
hi
So it seems that a trailing template literal executes its preceding function. I understand that template literals are code that is executed immediately, but this behavior makes no sense to me. Can someone explain this to me?
Maybe this piece of code can help you:
var test1 = 2;
var test2 = 3;
function fTest(strings, ...params){
strings.forEach((x) => console.log(`string param: ${x}`));
params.forEach((x, index) => console.log(`param ${index}: ${x}`));
}
const a = (f, param1, param2) => f`tagged ${param1} template ${param2} literals`;
a(fTest, test1, test2);
That mistery is a tagged template literal: essentially you're passing a template literals to your function, which will interpret the place holders as parameters, as well as the strings between them.
You can read here the documentation.
Another thing: if you want to ignore escape sequences you can use the raw function on the strings (see the example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With