Search code examples
javascriptnode.jsecmascript-6v8ecmascript-2016

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?


Solution

  •   ```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`