-1

According to the ES6 spec, the syntax

foo`Hello!`

should behave exactly like

foo('Hello!')

Putting a template literal after an expression triggers a function call, similar to how a parameter list (comma-separated values in parentheses) triggers a function call. The previous code is equivalent to the following function call (in reality, the function gets more information, but that is explained later).

Source

However, in the following snippet, binding a value to a function causes the 2 syntaxes to behave differently:

function alertParans() { alert(this)  }
function alertNoParans() { alert `${this}`  }

var executeParans = alertParans.bind('roman empire');
var executeNoParans = alertNoParans.bind('greek empire');

executeParans();
executeNoParans();

The first call prints 'roman empire' whilst the second will always just print a comma. Why?

Fiddle

iuliu.net
  • 6,666
  • 6
  • 46
  • 69
  • 1
    @Claies no, that's exactly what the question is about. He is using `alert` as a tagging function (which it was of course not intended for). – nils Nov 03 '16 at 19:36
  • 2
    [Don't use `alert()` for debugging.](http://stackoverflow.com/questions/8203473/why-is-console-log-considered-better-than-alert) – Michał Perłakowski Nov 03 '16 at 19:37
  • @Claies - No, the parentheses isn't needed -> https://jsfiddle.net/gcbhvqu5/1/ but in this case they solve the issue, which isn't the lack of parentheses, but using alert as a tag function – adeneo Nov 03 '16 at 19:38
  • ok I think I understand the dilemma here, sorry to be of confusion. – Claies Nov 03 '16 at 19:39
  • 3
    And just to be clear, swapping `alert` with `console.log` would show the difference clear as day, which is why you never use `alert` for debugging – adeneo Nov 03 '16 at 19:41

1 Answers1

7

You should read the example you linked to, as it says something different than you claim.

In the section it is stated that the following examples are equivalent:

tagFunction`Hello ${firstName} ${lastName}!`
tagFunction(['Hello ', ' ', '!'], firstName, lastName)

Now if you were to apply this to alert, it would look like this:

function alertParans() { alert(['', ''], this);  }
function alertNoParans() { alert`${this}`;  }

var executeParans = alertParans.bind('roman empire');
var executeNoParans = alertNoParans.bind('greek empire');

executeParans();
executeNoParans();

Now you get the comma in both cases, as the first argument of alert is now always an array with two empty strings. Why?

Because template literals are split into the contents before (''), during (this) and after ('') the interpolation.

nils
  • 25,734
  • 5
  • 70
  • 79