Mascara: Next Generation JavaScript compiler

Try it Download Buy About Documentation Blog Contact

Nullability

Compatibility note
non-null constraints are not at this point reliable when using global variables which are read from closure scopes. That is, a variable marked as not-nullable may still be read before it is assigned its initial value. We are working on a fix

Nullability is the question if a type allows the value null or not. The compiler tracks nullability, which eliminates a host of errors.

A variable of a non-nullable type has to be assigned an initial value.

For example, Date is nullable, while int is non-nullable. So:

var a : Date; // this is OK
var b : Date = null; // this is also OK
var c : int; // ERROR, has to be assigned a value
var d : int = null; // also ERROR, int cannot be null
var e : int = 7; // this is OK
Only the built-in types int, float, boolean and string are non-nullable. All other types (including user defined classes and types), are nullable by default.

It is however possible to make a type non-nullable by prefixing with a "!".:

var x : !Date = new Date(); // x cannot be null!
x = null; // ERROR

And, correspondingly, a non-nullable type can be declared nullable by prefixing with a ?:

var x : ?int = 7; 

X Try!
Mascara JavaScript Generated JavaScript

Translating...
Show compiler settings