Null and Undefined

JavaScript (and by extension TypeScript) has two bottom types : null and undefined. They are intended to mean different things:

  • Something hasn’t been initialized : undefined.
  • Something is currently unavailable: null.

Checking for either

Fact is you will need to deal with both. Just check for either with == check.

  1. /// Imagine you are doing `foo.bar == undefined` where bar can be one of:
  2. console.log(undefined == undefined); // true
  3. console.log(null == undefined); // true
  4. // You don't have to worry about falsy values making through this check
  5. console.log(0 == undefined); // false
  6. console.log('' == undefined); // false
  7. console.log(false == undefined); // false

Recommend == null to check for both undefined or null. You generally don’t want to make a distinction between the two.

  1. function foo(arg: string | null | undefined) {
  2. if (arg != null) {
  3. // arg must be a string as `!=` rules out both null and undefined.
  4. }
  5. }

One exception, root level undefined values which we discuss next.

Checking for root level undefined

Remember how I said you should use == null. Of course you do (cause I just said it ^). Don’t use it for root level things. In strict mode if you use foo and foo is undefined you get a ReferenceError exception and the whole call stack unwinds.

You should use strict mode … and in fact the TS compiler will insert it for you if you use modules … more on those later in the book so you don’t have to be explicit about it :)

So to check if a variable is defined or not at a global level you normally use typeof:

  1. if (typeof someglobal !== 'undefined') {
  2. // someglobal is now safe to use
  3. console.log(someglobal);
  4. }

Limit explicit use of undefined

Because TypeScript gives you the opportunity to document your structures separately from values instead of stuff like:

  1. function foo(){
  2. // if Something
  3. return {a:1,b:2};
  4. // else
  5. return {a:1,b:undefined};
  6. }

you should use a type annotation:

  1. function foo():{a:number,b?:number}{
  2. // if Something
  3. return {a:1,b:2};
  4. // else
  5. return {a:1};
  6. }

Node style callbacks

Node style callback functions (e.g. (err,somethingElse)=>{ /* something */ }) are generally called with err set to null if there isn’t an error. You generally just use a truthy check for this anyways:

  1. fs.readFile('someFile', 'utf8', (err,data) => {
  2. if (err) {
  3. // do something
  4. }
  5. // no error
  6. });

When creating your own APIs it’s okay to use null in this case for consistency. In all sincerity for your own APIs you should look at promises, in that case you actually don’t need to bother with absent error values (you handle them with .then vs. .catch).

Don’t use undefined as a means of denoting validity

For example an awful function like this:

  1. function toInt(str:string) {
  2. return str ? parseInt(str) : undefined;
  3. }

can be much better written like this:

  1. function toInt(str: string): { valid: boolean, int?: number } {
  2. const int = parseInt(str);
  3. if (isNaN(int)) {
  4. return { valid: false };
  5. }
  6. else {
  7. return { valid: true, int };
  8. }
  9. }

Final thoughts

TypeScript team doesn’t use null : TypeScript coding guidelines and it hasn’t caused any problems. Douglas Crockford thinks null is a bad idea and we should all just use undefined.

However NodeJS style code bases uses null for Error arguments as standard as it denotes Something is currently unavailable. I personally don’t care to distinguish between the two as most projects use libraries with differing opinions and just rule out both with == null.