Sterling Archer Sterling Archer - 4 years ago 156
Javascript Question

Backticks calling a function

I'm not sure how to explain this, but when I run


In google chrome, I get output like

VM12380:2 ["1", raw: Array[1]]

Why is the backtick calling the log function, and why is it making a index of
raw: Array[1]

Question brought up in the JS room by Catgocat, but no answers made sense besides something about templating strings that didn't really fit why this is happening.

Answer Source

It is called Tagged Template String in ES-6 more could be read about them Here, funny I found the link in the starred section of the very chat.

But the relevent part of the code is below (you can basically create a filter sort).

function tag(strings, ...values) {
  assert(strings[0] === 'a');
  assert(strings[1] === 'b');
  assert(values[0] === 0);
  return 'whatever';
tag `a${ 42 }b`  // "whatever"

Basically its merely tagging the "1" with console.log function, as it would do with any other function. The tagging functions accept parsed values of template strings and the values seperately upon which further tasks can be performed.

Babel transpiles the above code to

var _taggedTemplateLiteralLoose = function (strings, raw) { strings.raw = raw; return strings; };

console.log(_taggedTemplateLiteralLoose(["1"], ["1"]));

As you can see it in the example above, after being transpiled by babel, the tagging function (console.log) is being passed the return value of the following es6->5 transpiled code.

_taggedTemplateLiteralLoose( ["1"], ["1"] );

The return value of this function is passed to console.log which will then print the array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download