JavaScript TypeError – Can’t assign to property “X” on “Y”: not an object

This JavaScript exception can’t assign to property occurs in strict-mode only and this error occurs If the user tries to create a property on any of the primitive values like a symbol, a string, a number, or a boolean. Primitive values cannot be used to hold any property.

Message:

TypeError: can't assign to property "x" on {y}: not an 
           object (Firefox)
TypeError: Cannot create property 'x' on {y} (Chrome)

Error Type:

TypeError

Cause of Error: In strict-mode, a primitive value in the code is used to create a property on it. Primitive values can not hold properties.

Example 1: In this example, the string is used to create properties on it, So the error has occurred.



HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    'use strict';
    var GFG = "This is GeeksforGeeks";
    GFG.prop = {}; // error here
</script>

chevron_right


Output(in console):

TypeError: Cannot create property 'prop' on string 
'This is GeeksforGeeks'

Example 2: In this example, the boolean ‘true’ is used to create properties on it, So the error has occurred.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
    'use strict';
    var variableName = true;
    variableName.prop = {}; // error here
</script>

chevron_right


Output(in console):

TypeError: Cannot create property 'prop' on boolean 'true'

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.