A variable is said to be “
undefined” if it has been declared but not initialized. Whereas “
null” is assigned to a variable whose value is absent at that moment.
null value is assigned by programmer to indicate that variable has nothing inside of it, but intend to have value later in program execution.
var myVar; //Variable declaration without assigning any value to it console.log( myVar ); //undefined console.log( typeof(myVar) ); //undefined console.log( undeclaredVar ); //Uncaught ReferenceError: undeclaredVar is not defined
If we see a variable with value in undefined, then we know that:
- The variable has been declared in the program.
- There is no value assignment done for the variable.
- If we check the
typeof variable, it will be
- If a function returns
undefined, it didn’t returned any value.
null represents intentional absence of value. Conceptually, it’s very much like
null in other programming languages like Java, C# etc.
null expresses a lack of identification, indicating that a variable points to no object.
var myVar = null; //Variable declared and assigned to null console.log( myVar ); //null console.log( typeof(myVar) ); //object
Please note that
null is of type
object with a valid value, no properties, is non-mutable, and only a single instance of the same exists in the system at all times.
3. Using equality operators with null and undefined
Always remember to use strict equality operator (
=== ) for comparing variables with
undefined, when we want to clearly distinguish between
var myUndefinedVar; //undefined var myNullVar = null; //null myUndefinedVar == myNullVar; //true - which not correct as both are different myUndefinedVar === myNullVar; //false - correct behavior
4. Null evaluates to zero
One major difference between
undefined is in the way they are converted to primitive types.
nullis converted to zero (0) while performing primitive operations.
undefinedis converted to NaN.
var myUndefinedVar; //undefined var myNullVar = null; //null myUndefinedVar + 100; //NaN myNullVar + 100; //100
Drop me your questions in comments section.
Happy Learning !!