I’m creating a transpiler for a new programming language, named Serif. The transpiler outputs JavaScript code. Serif’s grammar does not contain a null literal. This poses a problem: Serif is intended to be interoperable with the JavaScript ecosystem, and JavaScript APIs sometimes use the null value.
I’m looking for a reliable way to access the null value. I’m currently using JSON.parse("null")
, which expresses my intent clearly. What are some other options? I’d like to find an approach that doesn’t require a function call.
In Serif, null
is an identifier. Unless shadowed, null
provides access to the JavaScript null value. The following code demonstrates the Serif equivalent of Object.create(null)
, and the JavaScript output.
example.serif (input file)
Object.create null;
example.js (output file)
const null$ = globalThis.JSON.parse("null");
Object.create(null$);
I’m looking for a simpler way to define null$
in the output file. (I’m using globalThis.JSON
rather than JSON
so JSON
can be used as a top-level variable in a Serif module if desired.)
2
Answers
Here are two other expressions that evaluate to
null
:I find these less clear than
JSON.parse("null")
.There are not that many operations that return
null
in the JS spec:Object.getPrototypeOf(Object.prototype)
– I would recommend this for your project, since that is pretty much the definition ofnull
in JS, "the missing object".null
./[]/.exec("")
or"".match(/[]/)
JSON.parse("null")
new Date(NaN).toJSON()