0

I have an assignment followed by a string interpolation:

var a = 3;
`${a} One two three`

"3 One two three"

If I leave ou the ; after the assignment then the code becomes invalid:

var a = 3
`${a} One two three`

VM573:2 Uncaught TypeError: 3 is not a function
    at <anonymous>:2:1

I thought that ; is mandatory only after {}... Can somebody explain the above please?

Boti
  • 3,275
  • 1
  • 29
  • 54
  • Related: http://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript – MTCoster Jan 27 '17 at 10:43
  • [Backticks calling a function](http://stackoverflow.com/questions/29660381/backticks-calling-a-function) – Andreas Jan 27 '17 at 10:45

1 Answers1

2

The 3 is being interpreted as a template literal tag. A template literal can be preceded with a "tag" which is a reference to a function. For example:

function tag() {
  return 'other string';
}
const s = tag`some string`;
console.log(s); // 'other string'

In your case, an error is thrown because 3 is not a function. The semicolon disambiguates the number and causes it to be parsed as exactly that - a number.

James Allardice
  • 164,175
  • 21
  • 332
  • 312