Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 549
Akhilesh Kumar Avatar asked Oct 14 '15 12:10

Akhilesh Kumar


People also ask

How do I fix uncaught SyntaxError unexpected identifier?

To solve the "Uncaught SyntaxError: Unexpected identifier" error, make sure you don't have any misspelled keywords, e.g. Let or Function instead of let and function , and correct any typos related to a missing or an extra comma, colon, parenthesis, quote or bracket.

What is uncaught SyntaxError unexpected token '<'?

The error Uncaught SyntaxError: Unexpected token < is most commonly caused by your site's code referring to an asset that is no longer available. Most commonly, this is due to a filename change in assets generated during your build.


1 Answers

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.

like image 88
Bergi Avatar answered Sep 21 '22 23:09

Bergi