Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 363
vitaly-t Avatar asked Dec 20 '17 10:12

vitaly-t


People also ask

What is `` in JS?

Although single quotes and double quotes are the most popular, we have a 3rd option called Backticks ( `` ). Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes.

What is the correct syntax of template strings in JavaScript?

Template literals are enclosed by backtick ( ` ) characters instead of double or single quotes. Along with having normal strings, template literals can also contain other parts called placeholders, which are embedded expressions delimited by a dollar sign and curly braces: ${expression} .

Can you nest template literals?

Nesting together multiple template literals can create unnecessary complexity, which reduces the code quality. The code becomes less readable and can cause maintainability issues overtime. A better practice, in these situations, is to move the nested template into a separate statement.

What is template string in ES6?

Backtick basics. ES6 introduces a new kind of string literal syntax called template strings . They look like ordinary strings, except using the backtick character ` rather than the usual quote marks ' or " . In the simplest case, they really are just strings: context.


1 Answers

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(`\`\``);
like image 173
Tushar Avatar answered Oct 09 '22 16:10

Tushar