hesoyam_
hesoyam_

Reputation: 23

JavaScript - Missing Syntax Error

I discovered this weird thing by an accident. I was writting some issue on GitHub and, as you know, to use some language highlighting in GitHub post you should encapsulate it in tripple grave accent. For example, if you want to use JavaScript, you should do this:

```JavaScript
// Your code
```

It will use JavaScript highlighting in your code snippet.

However, while I was writtin a post there, I accidentally copied whole code snipped from edit mode (including grave accents) and pasted it in js file. I've forgotten to remove accents, though. This is my code in js file:

function test(){
  ```JavaScript
  console.log(1);
  ```
}

It should be syntax error, of course. But, what surprises me is that Node.js compiled it without any errors. I couldn't believe. No cyntax error at all. How is this even possible?

So, I suppose tripple grave accent has special meaning in JavaScript (maybe multiline string like in Python?). I searchen on internet, but I found nothing. Why is EcmaScript allowing this? What is an example use of it?

Upvotes: 2

Views: 243

Answers (2)

zerkms
zerkms

Reputation: 254926

  ```JavaScript
  console.log(1);
  ```

is interpreted as per the 12.3.7.1 Runtime Semantics: Evaluation as the expression followed by a template literal.

So, the first empty template literal is evaluated to an empty string, then it is applied as a tag to the second template literal.

MemberExpression : MemberExpression TemplateLiteral

  1. Let tagRef be the result of evaluating MemberExpression.
  2. Let thisCall be this MemberExpression.
  3. Let tailCall be IsInTailPosition(thisCall).
  4. Return EvaluateCall(tagRef, TemplateLiteral, tailCall).

So it throws since a string is not a function.

This syntax is allowed so that it was possible to obtain tags as a result of an arbitrary expression evaluation, eg:

foo.bar`str`

Upvotes: -1

Rob M.
Rob M.

Reputation: 36511

Backticks are part of Javascript's grammar as of ES2015 and are used for template literals.

Your code does not contain any lexical syntax errors, the template version will throw an error when you run the function because of template tagging syntax attempting to evaluate the second and third templates. So to reiterate: no syntax errors exist, however, when you consider template tagging, the way this actually ends up getting evaluated is

""("Javascript\n console.log(1);\n")("")

Which will not work because "" is not a function. It is expecting characters before the backticks to be a tagging function. If you replaced the first set of backticks with a function, it would work:

function format(msg) {
   return function(secondMsg) {
     return "!!" + msg + secondMsg + "!!";
   };
}


console.log(format`Javascript\n console.log(1);\n```)

Upvotes: 3

Related Questions