Reputation: 6090
I'm working on a project which involves examining the AST provided by @babel/parser, and in a certain (not super-rare) case it's not behaving as I expected. This line of Javascript:
const var1 = undefined;
when processed by this command:
babelParser.parse(data, {
plugins: [ `jsx`, `classProperties` ],
sourceType: `unambiguous`,
});
gets transformed into this subtree:
{
"type": "VariableDeclarator", // expected
"start": 240,
"end": 256,
"loc": {
"start": {
"line": 17,
"column": 4
},
"end": {
"line": 17,
"column": 20
}
},
"id": {
"type": "Identifier", // also expected
"start": 240,
"end": 244,
"loc": {
"start": {
"line": 17,
"column": 4
},
"end": {
"line": 17,
"column": 8
},
"identifierName": "var1"
},
"name": "var1"
},
"init": {
"type": "Identifier", // dang, really?
"start": 247,
"end": 256,
"loc": {
"start": {
"line": 17,
"column": 11
},
"end": {
"line": 17,
"column": 20
},
"identifierName": "undefined"
},
"name": "undefined"
}
}
Why does the babel parser treat undefined
as a variable instead of "UndefinedLiteral"? (I mean, besides the fact that "UndefinedLiteral" doesn't seem to be a thing according to the AST spec)
Is there a way to change the type of this initial-value node? or will I have to add a special case to my code to look for Identifier
s with a value of "undefined"?
Upvotes: 2
Views: 529
Reputation: 161517
You can't because undefined
is not a special token in the JS grammar. It is perfectly valid to do
var undefined = 4;
console.log(undefined); // logs 4
so you'll need to check for an Identifier
called undefined
, and if you want to be careful also analyse the scope of the variable to see if it is actually the global undefined
binding, or a local one that could have some other value.
Upvotes: 2