The JavaScript error TypeError: null is not an object occurs when a property is accessed or a method is called on a null value. This specific error message is shown only on Safari. Other browsers display a different message for this error.
Error message:
TypeError: null is not an object (evaluating 'x.y') - Safari
TypeError: Cannot read properties of null (reading 'x') - Chrome
TypeError: x is null - Firefox
Error Type:
TypeError
What Causes TypeError: Null is Not an Object
The TypeError: null is not an object occurs when a property is read (or set) or a method is called on a null value. An object was expected in code but was not provided. Since null is not an object in JavaScript, using a null value when an object is expected does not work. A proper object must be provided in such situations.
TypeError: Null is Not an Object Example
Here’s an example of a TypeError: null is not an object thrown when trying to read a property of a null value:
var a = null;
console.log(a.b);
In the above code, the variable a has a null value. When the property b is attempted to be read on it, a TypeError: null is not an object is thrown:
TypeError: null is not an object (evaluating 'a.b')
How to Fix TypeError: Null is Not an Object
When such an error occurs, it means that a null value was provided where an object was expected. It should be ensured that the variable causing the error does not have a null value and is a proper object.
To avoid coming across situations where properties of null variables may be accessed accidentally, an if check should be added before dealing with such variables:
if (myVar !== null) {
...
}
Updating the previous example to include an if check:
var a = null;
if (a !== null) {
console.log(a.b);
}
Running the above code avoids the error since the property b is only accessed if a is not null.