Backticks (`…`) calling a function in JavaScript

JavascriptEcmascript 6Template StringsTemplate LiteralsTagged Templates

Javascript Problem Overview


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

console.log`1`

In google chrome, I get output like

console.log`1`
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.

Javascript Solutions


Solution 1 - Javascript

It is called Tagged Template 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 relevant part of the code is below (you can basically create a filtered sort).

function tag(strings, ...values) {
  assert(strings[0] === 'a');
  assert(strings[1] === 'b');
  assert(values[0] === 42);
  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 separately 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.

Solution 2 - Javascript

Tagged template literal:

The following syntax:

function`your template ${foo}`;

Is called the tagged template literal.


The function which is called as a tagged template literal receives the its arguments in the following manner:

function taggedTemplate(strings, arg1, arg2, arg3, arg4) {
  console.log(strings);
  console.log(arg1, arg2, arg3, arg4);
}

taggedTemplate`a${1}b${2}c${3}`;

  1. The first argument is an array of all the individual string characters
  2. The remaining argument correspond with the values of the variables which we receive via string interpolation. Notice in the example that there is no value for arg4 (because there are only 3 times string interpolation) and thus undefined is logged when we try to log arg4

Using the rest parameter syntax:

If we don't know beforehand how many times string interpolation will take place in the template string it is often useful to use the rest parameter syntax. This syntax stores the remaining arguments which the function receives into an array. For example:

function taggedTemplate(strings, ...rest) {
  console.log(rest);
}

taggedTemplate `a${1}b${2}c${3}`;
taggedTemplate `a${1}b${2}c${3}d${4}`;

Solution 3 - Javascript

Late to the party but, TBH, none of the answers give an explanation to 50% of the original question ("why the raw: Array[1]")

1. Why is it possible to call the function without parenthesis, using backticks?

console.log`1`

As others have pointed out, this is called Tagged Template (more details also here).

Using this syntax, the function will receive the following arguments:

  • First argument: an array containing the different parts of the string that are not expressions.
  • Rest of arguments: each of the values that are being interpolated (ie. those which are expressions).

Basically, the following are 'almost' equivalent:

// Tagged Template
fn`My uncle ${uncleName} is ${uncleAge} years old!`
// function call
fn(["My uncle ", " is ", " years old!"], uncleName, uncleAge);

(see point 2. to understand why they're not exactly the same)

2. Why the ["1", raw: Array[1]] ???

The array being passed as the first argument contains a property raw, wich allows accessing the raw strings as they were entered (without processing escape sequences).

Example use case:

let fileName = "asdf";

fn`In the folder C:\Documents\Foo, create a new file ${fileName}`

function fn(a, ...rest) {
  console.log(a); //In the folder C:DocumentsFoo, create a new file
  console.log(a.raw); //In the folder C:\Documents\Foo, create a new file 
}

What, an array with a property ??? ???

Yes, since JavaScript arrays are actually objects, they can store properties.

Example:

const arr = [1, 2, 3];
arr.property = "value";
console.log(arr); //[1, 2, 3, property: "value"]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSterling ArcherView Question on Stackoverflow
Solution 1 - JavascriptShrekOverflowView Answer on Stackoverflow
Solution 2 - JavascriptWillem van der VeenView Answer on Stackoverflow
Solution 3 - JavascriptludovicoView Answer on Stackoverflow