Why is the final template literal performing a function?

On this Twitter javascript 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

On the surface, it actually seems to make some decent meaning. a

is a function that takes some input f

and then does f``

. Which f``

is a complete mystery to me, so I threw it into the console and got this input.

(()=>{console.log('hi')})``

Hello

So it seems that the terminating template literal is fulfilling its previous function. I understand that template literals are code that gets executed immediately, but this behavior doesn't make any sense to me. Can someone explain this to me?

+3


source to share


1 answer


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);

      

This mistery is a tag with tags : essentially, you are passing boilerplate literature to your function, which will interpret the placeholders as parameters, as well as the strings in between.



You can read the documentation here .

Another thing: if you want to ignore escape sequences, you can use the raw

on function strings

(see example).

+1


source







All Articles