Null syntax sugar

Topics: Language Specification
Oct 2, 2012 at 2:34 AM
Edited Oct 2, 2012 at 2:36 AM

Two of the nice "syntax sugar" features that CoffeeScript presents over vanilla JavaScript relate to working with nulls.

The "?" operator coalesces nulls into the right hand side of the operator (similar to C#'s "??" operator). Example:

var a = null;

var b = a ?? 5;

//b is now 5


 The "?." is used for chains of property access. If any of the properties along the chain is null or undefined, undefined is returned. Example:


var a = {
  b: {
    c: 5
a.b = null;

var d = a?.b?.c ;

//d is now undefined rather than having thrown an exception.


I think it would be great for TypeScript to support both types of operators. They are just syntax sugar, but are still very useful and make very common boilerplate code much more concise. They also complement the ternary operator really nicely. 

(By the way, when is C# going to get the ".?" operator already???)

Oct 2, 2012 at 5:40 AM
Edited Oct 2, 2012 at 5:40 AM

+1. This would also ameliorate the issue discussed in

Oct 5, 2012 at 6:27 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.