The value 'undefined' denotes that a variable has been declared, but hasn't been assigned any value. On the other hand, 'null' refers to a non-existent object, which basically means 'empty' or 'nothing'. They're both values usually used to indicate the absence of something . Also, undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object .
Here we can see, first arr assigned some values and later assigned to null . Now value is null, but type is still an object.
When defining a variable that is meant to later hold an object , it is advisable to initialize the variable to null as opposed to anything else. That way, you can explicitly check for the value null to determine if the variable has been filled with an object reference at a later time.
Null Vs. Undefined
- The concrete difference between them is that null is explicit, while undefined is implicit.
- You can change the value of undefined by undefined=true; but you cannot change the value or null. This means that, null is object type where as undefined is undefined type.
- While performing primitive operations, null is converted to zero (0) whereas undefined is converted to NaN.
- You might consider undefined to represent a system-level, unexpected, or error-like absence of value and null to represent program-level, normal, or expected absence of value.