Why you should always use undefined, and never null
To write simple code you need to keep complexity and variation down. I find that where JavaScript offers alternatives, stick to one of them.
When a variable or a property on an object does not have a value it is undefined
, and for a value to be null
you need to assign it a null
value. As the variable already has no value there is absolutely no point in declaring that again with another type that in the end has the same meaning.
DRY
Don't repeat yourself. If you use null
in some cases, that it will require you to always check for both types each time we need to be able to tell undefined
or null
apart from other falsy values like 0
, ''
, or false
:
if (value === undefined || value === null) {
// Write some fallback code
}
Now imagine if you also want to check other values in that same if statement and the number combinations explode.
But document.querySelector('badtagname') returns null
Yes, it does, and it's a pain, but you can easily type that like this instead:
const element = document.querySelector('badtagname') || undefined;
In this way, you prevent any null
values from leaking into the rest of your code. The same would be needed for most other functions that fetch values from the DOM tree.
Do be careful though to not do this when working with numeric values or booleans as that could convert 0
to undefined
.
For those cases use typeof instead:
value = typeof value === 'number' ? value : undefined;
But I use null in other languages, it's familiar to me, why not use it in JavaScript as well? ...and undefined is longer to type
Sometimes you simply have to adopt the ways of the language you are working with, undefined
will always be there e.g. if you access a property that is missing myObject.iDoNotExist
and if you also assign another property on that same object the value null
you have just created a mixed mess.
As with all programming languages, several things were less well designed, and adding both undefined
and null
must have been one of them for JavaScript. I cannot figure out any other language that does this, or why they would.
But in JSON, at least, I can use null?
In JSON structures undefined
cannot be used as that type does not exist. You can hover assign null to a property {"someProperty": null}
, but why would you do that? If the property someProperty has no value, it's better to just exclude that property completely. Keeping such properties just increases the payload size that needs to be sent over the network or stored in a file without actually giving you any extra benefits.
Okay okay, this might make sense, how can I force all my colleagues into submission?
That is not a nice thought, anyhow, ask them nicely and then add the eslint-plugin-no-null plugin to your .eslintrc
:
{
"plugins": [
"no-null"
],
"rules": {
"no-null/no-null": 2
}
}
That is all!