DEV Community

Discussion on: The Difference Between Null and Undefined in JavaScript

 
analog_heart profile image
BP • Edited

Null is a valid value to represent anything that is nullable in nature. Undefined means it does not exist because it’s unset and was never set.

Does a person have a middle name? If yes, it will have an alpha value. If they do not have a middle name, it would be null. This is to say that the actual value is deliberately meant to be no middle name. This differs from undefined which is to say that the value does not exist because it was unset. Perhaps the form to enter the person details was only partially completed. Undefined means no deliberate choice has been applied to it. Null differs, if you’re using it correctly.

Taking this further, let’s say your data store is Mongo. You started by only collecting first and last name, and have thousands of documents that are missing this field. Later, you decide to include a middle name. Null is still valid, because not everyone has a middle name. You decide that, in order to facilitate data collection, you want to prompt any existing users that are missing this field. You could prompt those that have not yet taken an action because you can clearly see that the field is missing/undefined. They may choose to acknowledge that they have no middle name, at which point you’d save null to the document.

Now you want to integrate with a third party web api. That third party system is written in a strongly typed language (Java or C#). They only have the notion of null. You have forgotten to send over this middle name field because of how js’s type system works, and because of how the deserializers work, they do not know whether to reject the request or not. After all, they default to null if the field is not present in the json payload. The system has now made an incorrect assumption because of a limitation between being able to discern whether the data should be there but wasn’t or whether it was there and was intended to be null. This problem exists because there’s only one null.

Undefined is metadata that describes a js value that’s integral to its duck typing system. It’s got an entirely different purpose than null.

If you work in the field, how long have you been at it?