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.

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

Use the logical AND operator (&&) 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