Javascript undefined vs null
Today I am going to talk about the difference between javascript’s two of most famous primitive values, undefined and its counterpart null. Let's explore together what the differences are between null and undefined.
Null
- The value null represents the intentional absence of any object value.
- Null must be assigned.
- An interesting thing about null is that it expresses a lack of identification, indicating that the variable points to no object.
Undefined
- A variable that has not been assigned a value is of type undefined.
- A method or statement returns undefined if the evaluating variable does not have an assigned value
- A function returns undefined if a value is not returned
Analogy To Understand :
A metaphor or example scenario will help us to understand the underlying concept more thoroughly.
Let's imagine that you need to fill up an important form of some kind. You are also handed the same form which is being already filled to help you out. When you are reading through that reference form, you came up with a form field where you see the value N/A. This means that the question that is being asked in the form is not relatable to the person who answered that question. A perfect example will be the question where you are asked “Name of the husband/wife” and you are not married yet(Good for you). If you are not married, then you will simply put “N/A” as the answer because that question is not relatable to you if you are unmarried. That is null in javascript.
Now imagine when you are reading through the form which was already filled up, you stumbled upon a question where there is no answer given for that question. Now, this is different from the previous example. Here there is no value, even no “N/A”. This means that the person who has filled up the form, either doesn’t understand the question very well or doesn’t know the answer to this question. For the case where “N/A” is the answer to the question, there is at least some value. But when any answer is left unanswered or not filled, there is actually no value at all. That is undefined in javascript
Code Example :
If we look at some code in javascript, the given metaphor will become more clear.
var someVariable;
console.log(someVariable); -> this will print undefined
var someOtherVariable = null;
console.log(someOtherVariable); -> this will print null
In the first example, a variable is declared but not defined or assigned with any kind of value. The dictionary meaning of undefined is something like this “not clear or defined”.
Comments
Post a Comment