I want to know what the difference is between null
and undefined
in JavaScript.
When you declare a variable in javascript, it is assigned the value undefined
. This means the variable is untouched and can be assigned any value in future. It also implies that you don't know the value that this variable is going to hold at the time of declaration.
Now you can explicitly assign a variable null
. It means that the variable does not have any value. For example - Some people don't have a middle name. So in such a case its better to assign the value null to the middlename variable of a person object.
Now suppose that someone is accessing the middlename variable of your person object and it has the value undefined
. He wouldn't know if the developer forgot to initialize this variable or if it didn't have any value. If it has the value null
, then the user can easily infer that middlename doesn't have any value and it is not an untouched variable.