-1

If I enter this expression in the browser console (with grave accent):

Math.sin`1`

It will return:

0.8414709848078965

But if I enter this expression (with single quote):

Math.sin'1'

It will throw this error:

SyntaxError: Unexpected number

Why does this error happen?

Xiddoc
  • 3,369
  • 3
  • 11
  • 37
Hrundel
  • 1
  • 1
  • ``tag`template literal`︁`` is [specifically part of the template literal syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates). It doesn’t work for other string literals. – Ry- Jun 07 '18 at 06:51
  • Thanks you! There was no link to tags from template string section in my manual. – Hrundel Jun 07 '18 at 07:03

2 Answers2

2

That's what's called a tagged template literal:

fn`string`

assuming fn is a function, will simply result in fn being called with string as the first argument.

Tagged template literal functions are more useful when you have ${ .. } replacements to make. From the MDN example:

var person = 'Mike';
var age = 28;

function myTag(strings, personExp, ageExp) {
  var str0 = strings[0]; // "that "
  var str1 = strings[1]; // " is a "
  return str0 + personExp + str1 + (
    ageExp > 99
    ? 'centenarian'
    : 'youngster'
  );
}

console.log(myTag`that ${ person } is a ${ age }`);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

tag`template literal` is specifically part of the template literal syntax. It doesn’t work for other string literals.

Ry-
  • 218,210
  • 55
  • 464
  • 476