mathjs icon indicating copy to clipboard operation
mathjs copied to clipboard

Support nullish coalescing operator ?? in mathjs expression language

Open gwhitney opened this issue 11 months ago • 1 comments

Describe the suggested feature Currently x ?? 0 is a syntax error. It would be handy if this meant the nullish coalescing operator denoted by ?? in JavaScript. For example, one could then do object lookup with a fallback : {foo: 7, bar: 3}["baz"] ?? 0.

Current workaround nullish(x, y) = (x == null or x == undefined) ? y : x; nullish(null, 0)

I am not aware of a short way to test for null or undefined unlike x == null in JavaScript which is true if x is either null or undefined; in mathjs expression language it is true when x is null and false when x is undefined.

gwhitney avatar Jan 18 '25 23:01 gwhitney

Having the nullish coalescing operator would be great!

josdejong avatar Feb 28 '25 15:02 josdejong

Hey @josdejong

I would like to give this a shot

ikemHood avatar Jun 26 '25 15:06 ikemHood

As the suggested syntax enhancement has been approved by the head of MathJS, a PR is welcome. Of course be sure that the change does not disrupt the ternary operator x ? 1 : 0 and add tests for variants like x ?? 0, x??0, etc.

gwhitney avatar Jun 26 '25 19:06 gwhitney

Thanks @ikemHood , please let us know if you need any pointers.

josdejong avatar Jun 27 '25 14:06 josdejong

I'd love to work on this as I have experience with parsers and expression evaluators. I'll add ?? support by updating the tokenizer, parser, and evaluator with proper precedence and tests.

Anuragyadav622003 avatar Jun 29 '25 11:06 Anuragyadav622003

I believe @ikemHood is working on it; you should check with that person to avoid duplicating effort.

gwhitney avatar Jun 30 '25 21:06 gwhitney

Yes. @gwhitney. made a PR (#3497)

waiting for a review

ikemHood avatar Jul 01 '25 03:07 ikemHood

I have experience in JavaScript. I want to fix this problem.

AbiodunVlad avatar Jul 01 '25 08:07 AbiodunVlad

@AbiodunVlad, we appreciate your interest in MathJS and in this issue. However, as @ikemHood has submitted a PR for it that seems at least for the time being to be on the right track, we would not recommend your duplicating effort by working on this issue. You may find others that are of interest to you.

gwhitney avatar Jul 01 '25 21:07 gwhitney

Published now in v14.8.0

josdejong avatar Sep 24 '25 09:09 josdejong