Monday 10 June 2024

When an absence of value doesn't equate to a NULL

In programming, it can be easy to confuse the NULL value some something similar, such as undefined or (with regard to string literals) empty. This is because people tend to classify values into two categories - either something has value, or it has no value.

But NULL is a value in itself... and that value is explicitly no value. Confusing? I can see how it would be.

NULL values vs undefined

Let's say I gave you a voting slip in an election, where you could choose only one candidate out of two choices.

Not voting is not the same
as voting for no one.

Did you choose the first, or second candidate? That's the value of your choice. If your choice was, say, a variable named choice, and the candidates were numbered 0 or 1, the value of choice would either be 0 or 1.

But what if you decided not to vote, or hadn't had a chance to vote yet? Then, if this was JavaScript, the default value for choice would be undefined, because a value has not yet been assigned to choice.

What if you decided to invalidate your vote by spoiling it or just not filling it in? Then you would have voted. A value would be assigned to choice. And since you invalidated the vote, that means you voted for neither. But your vote was still registered. Whereas undefined means that you hadn't voted yet, in this case you had voted and you had explicitly not voted for either candidate. This would be more akin to a NULL value; you explicitly choose not to make a choice. But that in itself is a choice, therefore the variable choice now has a value. And that value, of course, is no value. Or NULL.

NULL values vs empty strings

Similarly an empty string is not the same as a NULL. Both an empty string and a NULL have values. The NULL has, as before, a value of no value. And the empty string is simply a string with no characters, but that does not change the fact that it is a string.

A string without characters
is still a string, not a NULL.

Try running a string operation on an empty string...
var str = "";
console.log(str.length) //gives you 0.


...and on a NULL.
var str = null;
console.log(str.length) //gives you an error.


Trying to get the length property from str in the first example will give you a 0, because it is a string with zero characters. In the second example, you get an error because a NULL is not a string object, and therefore does not have a length property.

To expand on the above, a NULL is not only not a string, it is also not an integer, or a float, or a Boolean. A NULL is a NULL.

The Takeaway

The takeaway from this, of course, is that NULL values are NULL values... not empty strings or 0s. NULL values are values that basically mean "no value", which is not the same as actually having no value.

It's NULL or never,
T___T


No comments:

Post a Comment