Can’t define property object not extensible

In JavaScript, we sometimes get the following exception:

“can’t define property “x”: “obj” is not extensible”

This error occurs when an object is no longer extensible so that it will never have properties beyond the ones it had at the time it was marked as non-extensible.

We get slightly different message in different browser:

TypeError: Cannot create property for a non-extensible object (Edge)
TypeError: cannot define property "x": "obj" is not extensible (Firefox)
TypeError: Cannot define property: "x", object is not extensible. (Chrome)

Reason of the issue:

By default an object is extensible and new properties can be added to it. However, if we use Object.preventExtensions() on an object then it is no longer extensible.

if we try to add a property to the object it will throw the exception:

var obj = { }; 
Object.preventExtensions(obj); 

Object.defineProperty(obj, 
  'name', { value: "Joe Smith" }
);
// TypeError: can't define property "name": "obj" is not extensible

Solution of the issue:

To solve this error, we will either need to remove the call to Object.preventExtensions() on the object, or move the add property call before the Object.preventExtensions().

var obj = { }; 
Object.defineProperty(obj, 
  'name', { value: "Joe Smith" }
);
Object.preventExtensions(obj);