Categories
JavaScript Answers

How to Fix the ‘TypeError: can’t assign to property “x” on “y”: not an object’ Error in Our JavaScript App?

Spread the love

Sometimes, we may run into the ‘TypeError: can’t assign to property "x" on "y": not an object’ when we’re developing JavaScript apps.

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

Fix the ‘TypeError: can’t assign to property "x" on "y": not an object’ When Developing JavaScript Apps

To fix the ‘TypeError: can’t assign to property "x" on "y": not an object’ when we’re developing JavaScript apps, we should make sure that we’re creating a property on an object instead of a primitive value.

On Firefox, the error message for this error is TypeError: can't assign to property "x" on {y}: not an object.

On Chrome, the error message for this error is TypeError: Cannot create property 'x' on {y}.

For instance, if we have:

'use strict';

const foo = "string";
foo.bar = {};

then we’ll get the error since foo is a string, so we can’t add new properties to it.

To fix this, we should add properties to an object:

'use strict';

const foo = {};
foo.bar = {};

Conclusion

To fix the ‘TypeError: can’t assign to property "x" on "y": not an object’ when we’re developing JavaScript apps, we should make sure that we’re creating a property on an object instead of a primitive value.

On Firefox, the error message for this error is TypeError: can't assign to property "x" on {y}: not an object.

On Chrome, the error message for this error is TypeError: Cannot create property 'x' on {y}.

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 *