Home > Back-end >  Javascript template literal strange behaviour
Javascript template literal strange behaviour

Time:02-16

Why is the following code syntactically correct?

let v = ``(oldVal-newVal) / 1000;

It gives the following runtime error:

Uncaught TypeError: "" is not a function

My guess is the `` becomes a tagged template, and "" would be tag name, but not sure. (I got to this by accidentally typing it instead of the Ctrl ` shortcut in VSCode. Took a day to find it. ;)

CodePudding user response:

A tagged template takes the form:

function myTaggedTemplate(...) { }

And is called with:

myTaggedTemplate`...`

You have a variable name referencing a function on the left, and a template string on the right.


What you have is equivalent to:

const left = ``;
left(oldVal-newVal);

It errors with "is not a function" because it is a string, not a function.

It is syntactically valid because you can try to treat the result of any expression as a function. Determining if it is a function or not happens at run-time.

  • Related