The difference between undefined and null is undefined
means a variable has been declared but has not yet been assigned a value, where null
is an assignment value. It can be assigned to a variable as a representation of no value.
undefined
: It means that the object doesn’t have any value, therefore undefined. This occurs when you create a variable and don’t assign a value to it.
null
: It means that the object is empty and isn’t pointing to any memory address.
# | Undefined | Null |
---|---|---|
Value | undefined | null |
Type | undefined | object |
Occurrence | Occurs when a variable has been declared but has not been assigned a value. | Occurs when a developer intentionally sets a variable with no value. |
Usage | Typically represents a variable that has not been initialized or a non-existent property of an object. | Typically represents a deliberate absence of any object value or the result of an operation that intentionally does not return a value. |
Equality Check | When compared with double or triple equals, it returns true when compared with null or undefined. | When compared with double or triple equals, it returns true only when compared with null. |
Object Reference | Cannot be assigned as a property of an object, and when an attempt is made to do so, it will result in an error. | Can be assigned as a property of an object, and will not result in an error. |
Default Value | When a function parameter is not passed a value, its default value is undefined. | When assigning a default value to a function parameter, null can be used to represent an intentional absence of a value. |
Difference between undefined and null in JavaScript
From the simple example code, it is clear that undefined
and null
are two distinct types: undefined
is a type itself (undefined) while null
is an object.
<!DOCTYPE html>
<html>
<body>
<script>
var testVar;
console.log(testVar);
console.log(typeof testVar);
var testVar = null;
console.log(testVar);
console.log(typeof testVar);
</script>
</body>
</html>
Output:
How to check for an undefined or null variable in JavaScript?
Answer: The most efficient way to test for “value is null
or undefined
” is
if ( some_variable == null ){
// some_variable is either null or undefined
}
So these two lines are equivalent:
if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}
Comment if you have any doubts or suggestions on this JS undefined and null topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version