vitaly-t
vitaly-t

Reputation: 25860

Nested template string error in NodeJS

Why does the following line result in a run-time error in Node.js?

var a = ````;

throws:

TypeError: "" is not a function


Tested with Node.js versions 4.x, 6.x, 8.x and 9.x

Upvotes: 8

Views: 453

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

It's because you have two template literals immediately next to each other without any kind of joining expression. The parser recognizes that as a tagged function call, like String.raw`stuff here`. The first `` is evaluated, results in "", and then the JavaScript engine tries to call that empty string as a function, passing in the processed template literal. Since the empty string isn't a function, you get an error.

You get the same error more directly using ""``. :-)

Upvotes: 3

Tushar
Tushar

Reputation: 87203

First two backticks are empty string while the next two will act as tagged template literals which will invoke the function before it. As ""(empty string) is not an invokable function, it throws an error.

Backticks calling a function

To nest backticks in template literal, escape it by preceding it with forward slash

console.log(`\`\``);

Upvotes: 4

Related Questions