JavaScript TypeError – Can’t define property “X”: “Obj” is not extensible
This JavaScript exception can’t define property “x”: “obj” is not extensible occurs when Object.preventExtensions() used on an object to make it no longer extensible, So now, New properties can not be added to the object.
Message:
TypeError: Cannot create property for a non-extensible object (Edge) TypeError: can't define property "x": "obj" is not extensible (Firefox) TypeError: Cannot define property: "x", object is not extensible. (Chrome)
Error Type:
TypeError
Cause of Error: After the Object.preventExtensions() method applied on an object, New properties are added to the object, Which is not permissible.
Example 1: In this example, the new property is being added after the Object.preventExtensions() method applied, So the error has occurred.
HTML
< script > 'use strict'; var GFG_Obj = {'name': 'GFG'}; Object.preventExtensions(GFG_Obj); GFG_Obj.age = 22; // error here </ script > |
Output(in console):
TypeError: Cannot create property for a non-extensible object
Example 2: In this example, the new property is being added using defineProperty() method after the Object.preventExtensions() method applied, So the error has occurred.
HTML
< script > 'use strict'; var GFG_Obj = {'name': 'GFG'}; Object.preventExtensions(GFG_Obj); // error here Object.defineProperty(GFG_Obj, 'person', { dob: "02/11/1997" } ); </ script > |
Output(in console):
TypeError: Cannot define property 'person': object is not extensible