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:
- $ node
- > var esprima = require('esprima')
- > esprima.parseScript('if (x) function y() {}')
- Script {
- type: 'Program',
- body:
- [ IfStatement {
- type: 'IfStatement',
- test: [Object],
- consequent: [Object],
- alternate: null } ],
- 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.