To myself… May I help other fellow coders use undefined and null appropriately through this short article.
Variable declaration and initialisation
Before having a solid understanding of the differences between
null, it’s important to know the steps in declaring and initialising a variable.
Declaring is giving the variable a name.
Initialising is giving the variable a value
catName = "Felicia";
Combining these two statements, we have a variable that has been declared with a name
catName and a value of
let catName; // declaration catName = "Felicia"; // initialisation
Technically speaking, undefined means lack of an assigned value.
You can think of undefined as the default value of variable when it has not been assigned a value.
Rephrased slightly, undefined means either (1) variable is not declared (2) variable is declared but no value is assigned to it.
With null, it means variable is declared and the coder explicitly set the value to
Null can be used to mean that the value does exist but at this point it is not yet known. For example an online form with an age field. Setting the age variable with null value means we know that the person’s age exists but we don’t know it yet (since the person has not filled in the details yet).
Difference in data types
Something to think about