3

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?

  • It's a tagged template literal: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals_and_escape_sequences – cartant Jul 28 '17 at 22:14

1 Answers1

1

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

Marco Luzzara
  • 5,540
  • 3
  • 16
  • 42