Browser Compatibility

In a certain specific case, Esprima parser intentionally does not throw an exception (indicating a syntax error) although the input being parsed is not valid. This is to achieve an implementation compatibility with major web browsers. For further details, refer to the official ECMAScript 2015 Language Specification, Section B.3.3 on Block-Level Function Declarations Web Legacy Compatibility Semantics:

Prior to ECMAScript 2015, the ECMAScript specification did not define the occurrence of a FunctionDeclaration as an element of a Block statement’s StatementList. However, support for that form of FunctionDeclaration was an allowable extension and most browser-hosted ECMAScript implementations permitted them.

This is illustrated in the following example:

  1. $ node
  2. > var esprima = require('esprima')
  3. > esprima.parse('if (x) function y() {}')
  4. Program {
  5. type: 'Program',
  6. body:
  7. [ IfStatement {
  8. type: 'IfStatement',
  9. test: [Object],
  10. consequent: [Object],
  11. alternate: null } ],
  12. sourceType: 'script' }

In the above example, Esprima parser returns a syntax tree for the code (it does not throw an exception) even though the input is invalid according to the specification, i.e. declaring a function inside the block of an If statement is not possible. In this case, the behavior of Esprima is the same as the popular web browsers such as Firefox, Chrome, Safari, and many others.