6

I'm using tagged template strings in following code

var a = 5;
var b = 10;
var pp="";
function tag(strings, ...values) {
  pp+=strings[0]; // "Hello "
  pp+=strings[1]; // " world "
  pp+=values[0];  // 15
  pp+=values[1];  // 50

  console.log(pp+"Bazinga!");
}

tag`Hello ${ a + b } world ${ a * b}`;

but it gives

Uncaught SyntaxError: Unexpected token ...(…)

On function tag(strings, ...values) {

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Akhilesh Kumar
  • 9,085
  • 13
  • 57
  • 95
  • 3
    What JS engine are you testing your ES6 code in? – Quentin Oct 14 '15 at 12:38
  • Are you using a transpiler? Do template strings work in your environment without tags? – Bergi Oct 14 '15 at 12:46
  • yes it does, I'm using latest chrome console – Akhilesh Kumar Oct 14 '15 at 12:48
  • [Worksforme](http://babeljs.io/repl/#?experimental=false&evaluate=true&code=var%20a%20%3D%205%3B%0D%0Avar%20b%20%3D%2010%3B%0D%0Afunction%20tag(strings%2C%20...values)%20%7B%0D%0A%20%20var%20pp%3D%22%22%3B%0D%0A%20%20pp%2B%3Dstrings%5B0%5D%3B%20%2F%2F%20%22Hello%20%22%0D%0A%20%20pp%2B%3Dstrings%5B1%5D%3B%20%2F%2F%20%22%20world%20%22%0D%0A%20%20pp%2B%3Dvalues%5B0%5D%3B%20%20%2F%2F%2015%0D%0A%20%20pp%2B%3Dvalues%5B1%5D%3B%20%20%2F%2F%2050%0D%0A%0D%0A%20%20console.log(pp%2B%22Bazinga!%22)%3B%0D%0A%7D%0D%0A%0D%0Atag%60Hello%20%24%7B%20a%20%2B%20b%20%7D%20world%20%24%7B%20a%20*%20b%7D%60%3B) – Bergi Oct 14 '15 at 12:49
  • 3
    Chrome doesn't support rest parameters yet: https://kangax.github.io/compat-table/es6/#test-rest_parameters – Andreas Oct 14 '15 at 12:53

1 Answers1

4

As the syntax error Unexpected token ... tells you, not the tag is the problem, but the usage of the rest operator. Try the following:

var a = 5,
    b = 10;
function tag(strings) {
  var pp="";
  pp+=strings[0]; // "Hello "
  pp+=strings[1]; // " world "
  pp+=arguments[1];  // 15
  pp+=arguments[2];  // 50

  return pp+"Bazinga!";
}

console.log(tag`Hello ${ a + b } world ${ a * b}`);

According to the ES6 compatibility table, you need to enable rest syntax via the harmony flag in the current Chrome.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375