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

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    'use strict';
  
    var GFG_Obj = {'name': 'GFG'};
    Object.preventExtensions(GFG_Obj);
  
    GFG_Obj.age = 22; // error here
</script>

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    'use strict';
  
    var GFG_Obj = {'name': 'GFG'};
    Object.preventExtensions(GFG_Obj);
  
    // error here
    Object.defineProperty(GFG_Obj, 
      'person', { dob: "02/11/1997" }
    );
</script>

chevron_right


Output(in console):

TypeError: Cannot define property 'person': object is not extensible

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.