Looking for Champion: Null Coalescing (??) and Null Conditional Member Access (?.) operators

Arash Motamedi arash.motamedi at gmail.com
Wed Dec 20 08:03:49 UTC 2017

I’d like to propose two new operators that I’ve appreciated using in C#,
with appropriate modifications for Ecmascript.

?? Null-Coalescing Operator

The ?? operator is called the null-coalescing operator. It returns the
> left-hand operand if the operand is not null or undefined; otherwise it
> returns the right hand operand. (modified excerpt from C# definition, here
> <https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operator>
> .)


let u = undefined;
let nu = u ?? 0;
//  nu = (u !== undefined && u !== null) ? u : 0

let n = null;
let nn = n ?? "Default";
//  nn = (n !== undefined && n !== null) ? n : "Default";

let p = someObj.someProp ?? "Hello";
//  p = (someObj.someProp !== undefined && someObj.someProp !== null) ?
someObj.someProp : "Hello";

The ?? operator allows for a very terse syntactic representation of a
rather common statement, and its value becomes very clear when evaluating
and accessing properties on objects, as illustrated in the 3rd example
above. For credit, comparison, and further details, please review the C#
null coalescing operator information here

?. Null Conditional Member Access and ?[ Null Conditional Index Access

Used to test for null or undefined before performing a member access (?.)
> or index (?[) operation. (modified excerpt from C# definition here
> <https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators>
> .)


let n = null;
let nn = n?.name;
//  nn = (n.name !== null && u.name !== undefined) ? u.name : u.name;

let p = {name: "John"};
let l = p.lastName?.length;
//  l = (u.lastName !== null && u.lastName !== undefined) ?
u.lastName.length : u.lastName;

The ?. and ?[ operators allow for graceful access (as opposed to
null/undefined reference errors) to object members, and are particularly
useful when used in a chained manner. For credit, comparison, and further
details, please review the C# null conditional member access operator
information here

Combining the above operators can enable very concise syntax for checking
against null/undefined and providing default values in a graceful manner.

let lastNameLength = person.lastName?.length ?? 0;
let cityToUppercase = person.address?.city?.toUpperCase() ?? "N/A";

Looking forward to working with the community and hopefully bringing these
two operators to the language.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20171220/87293c3e/attachment.html>

More information about the es-discuss mailing list