javascriptgoogle-chromeecmascript-6template-stringstagged-templates

Trying to use Tagged template strings gives 'Uncaught SyntaxError: Unexpected token'


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


Solution

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