Categories
JavaScript Answers

How to Fix the ‘TypeError: can’t access property “x” of “y” ‘ Error in Our JavaScript App?

Spread the love

Sometimes, we may run into the ‘TypeError: can’t access property "x" of "y"’ when we’re developing JavaScript apps.

In this article, we’ll look at how to fix the ‘TypeError: can’t access property "x" of "y"’ when we’re developing JavaScript apps.

Fix the ‘TypeError: can’t access property "x" of "y"’ When Developing JavaScript Apps

To fix the ‘TypeError: can’t access property "x" of "y"’ when we’re developing JavaScript apps, we should make sure the object we’re trying to access the property for isn’t undefined or null.

On Edge, the error message for this error is TypeError: Unable to get property {x} of undefined or null reference.

On Firefox, the error message for this error is TypeError: can't access property {x} of {y}, TypeError: {y} is undefined, can't access property {x} of it, or TypeError: {y} is null, can't access property {x} of it.

For instance, if we have:

const foo = undefined;
foo.substring(1);

const foo = null;
foo.substring(1);

then we’ll get this error since foo is either undefined or null.

Instead, we check if the variable isn’t undefined or null before accessing its properties:

if (typeof foo !== 'undefined') {
  // ...
}

We check that foo isn’t undefined with the typeof` operator.

Also, we can use the optional chaining operator (?.) to access a property:

foo?.substring(1)

then no error will be thrown if foo is undefined or null.

Conclusion

To fix the ‘TypeError: can’t access property "x" of "y"’ when we’re developing JavaScript apps, we should make sure the object we’re trying to access the property for isn’t undefined or null.

On Edge, the error message for this error is TypeError: Unable to get property {x} of undefined or null reference.

On Firefox, the error message for this error is TypeError: can't access property {x} of {y}, TypeError: {y} is undefined, can't access property {x} of it, or TypeError: {y} is null, can't access property {x} of it.

We can use the optional chaining operator (?.) to access a property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *