Difference between undefined and null in Javascript- When to use what?


Difference between undefined and null in Javascript- When to use what?

This is one of the most confusing topics in the Javascript world. Beginners finds it difficult to understand when to use what.

Kindly read my below post for understanding undefined.

Understanding undefined in Javascript

Null is like N/A(not applicable). It’s a non-value, nothing. Both undefined and null indicates absence of value. After declaring a variable but not defined, variable is undefined. But, suppose you want that variable to be non-value, then use null.

Now when to use what. Best example to consider is a paper form. The form has 3 fields first name, middle name, last name. Suppose a person fills the form, and you found that the middle name field is empty. Now how to determine that the person filling the form does not have a middle name(which in this case the person should deliberately skip filling middle name) or the person forgot to fill in the middle name. So, basically in Javascript world if the user forgets to fill middle name then it’s undefined, however if the user sees the middle name but since he/she does not have a middle name so N/A is filled. N/A(also, nothing) in Javascript world is null. That means user has provided some value and that value represents a non-value.

So basically, when the variable is undefined that means the variable is declared but not defined, however null variable in Javascript means the variable wishes to be in defined state but wants to hold a non-value.

null primitive data-type in Javascript has only one value,i.e. null. null actually represents non-value kind of thing. So, null is a middle state between undefined and value state(Number, String, Boolean).

var rai=null;

It will print null.

About Anoop Kumar Rai