Null should mean something

It’s a common pattern in JavaScript to do this to assign a default value to a variable :

var theThing = someThing || defaultThing;

In other words, if someThing has a ‘falsey’ value (false, null , undefined , ” ,0) then the value of defaultThing will be assigned to theThing.

What is often mean by this pattern is :

var theThing = typeof someThing === typeof undefined ? defaultThing : theThing;

where the defaultThing is only assigned if someThing is undefined. Using the first pattern where the value of someThing is a legitimate falsey value (like 0), would overwrite that value with the default – presumably not the intended result.

Undefined versus null

Many developers are inconsistent in their use of null and end up treating undefined and null (or indeed any other falsey value) in the same way. I know for sure that I am occasionally guilty of this.  In fact, null and undefined are even different types (object versus undefined), so using them interchangeably seems reckless.

Defining a variable, with no assignment causes it to be undefined, whereas null has to be specifically assigned. Accessing a property that does not exist also returns undefined.

var myVar, myObject = {} , myNull = null;

typeof myVar; // undefined
typeof myObject; // object
typeof myNull; // object
typeof myObject.someProperty; // undefined

Testing for falsey values rather than specifically testing for undefined versus null can lead to errors and also wastes potentially important information.

Making null mean something

In many cases, null is a perfectly acceptable value, whereas undefined means the value is not yet known.

var myValue;

function getValue (key) {
// this returns null if not matching key found
return PropertiesService.getUserProperties().getProperty(key);
}
// only assign a default value of we haven’t already tried to
if(typeof myValue === typeof undefined) {
myValue = getValue(‘myKey’) || ‘myDefaultValue’;
}

Consistent usage will help get value out of the difference between undefined and null that JavaScript so helpfully provides

  • If you haven’t yet tried to assign a value to a variable, it should be undefined, meaning further action may be required to ascertain the value.
  • If you’ve tried, and the source of data to assign to a value is missing, use null, meaning no further action is required.
For more stuff both like and different from this see Desktop Liberation

Author: brucemcp

Leave a Reply

Your email address will not be published. Required fields are marked *