Why is this an issue?

In JavaScript, null and undefined are primitive values that do not have properties or methods. When accessing a property on a null or undefined value, JavaScript tries to access the property of an object that does not exist, which results in a TypeError.

This can cause the program to crash or behave unexpectedly, which can be difficult to debug.

How to fix it

Code examples

Noncompliant code example

let foo = null;
console.log(foo.bar); // Noncompliant: TypeError will be thrown

Compliant solution

The simplest solution is to check in a if condition the equality to null or undefined. With the abstract equality operator it is not required to check both, as these operators consider null and undefined to be equals.

let foo;
if (foo != null) {
  console.log(foo.bar);
}

Also, the logical AND operator (&&) can be used to check if a variable is truthy before attempting to access its properties. The expression will short-circuit and return the falsy value instead of attempting to access its properties.

let foo = null;
console.log(foo && foo.bar);

Alternatively, use the optional chaining operator (?.) to check if the variable is null or undefined before attempting to access its property. This operator is more readable and concise, especially when dealing with nested properties.

let foo = null;
console.log(foo?.bar);

Resources

Documentation