skip to Main Content

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


  1. Chosen as BEST ANSWER

    Here are two other expressions that evaluate to null:

    > /x/.exec("")
    null
    
    > "".match(/x/)
    null
    

    I find these less clear than JSON.parse("null").


  2. There are not that many operations that return null in the JS spec:

    1. The final link of every prototype chain, e.g. Object.getPrototypeOf(Object.prototype) – I would recommend this for your project, since that is pretty much the definition of null in JS, "the missing object".
    2. The "null" literal, i.e. null.
    3. Regex matches, e.g. /[]/.exec("") or "".match(/[]/)
    4. JSON parsing, e.g. JSON.parse("null")
    5. The JSON value of invalid dates, e.g. new Date(NaN).toJSON()
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search