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

1

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

Magnanimity answered 14/10, 2015 at 12:36 Comment(5)
What JS engine are you testing your ES6 code in?Belgium
Are you using a transpiler? Do template strings work in your environment without tags?Diameter
yes it does, I'm using latest chrome consoleMagnanimity
WorksformeDiameter
Chrome doesn't support rest parameters yet: kangax.github.io/compat-table/es6/#test-rest_parametersAnticlinal
D
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.

Diameter answered 14/10, 2015 at 12:54 Comment(2)
Cool, it worked but didn't got how to enable rest syntaxMagnanimity
@AkhileshKumar Put this link in the address bar and activate the highlighted option: chrome://flags/#enable-javascript-harmonyAnticlinal

© 2022 - 2024 — McMap. All rights reserved.