JavaScript TypeError – Setting getter-only property “x”

This JavaScript exception setting getter-only property works in strict-mode only and occurs if the user tries to set a new value to a property for which only a getter is specified.

Message:

TypeError: Assignment to read-only properties is 
           not allowed in strict mode (Edge)
TypeError: setting getter-only property "x" (Firefox)
TypeError: Cannot set property "prop" of #<Object> 
           which has only a getter (Chrome)

Error Type:

TypeError

Cause of the Error: The user is trying to set a new value to a property for which only a getter is defined.

Example 1: In this example, the getter method is defined for the object. Property can not be accessed directly.



HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
"use strict";
function GFG_Fun() { 
  var temp = null; 
  Object.defineProperty(this, 'temp', { 
    get: function() {
      return temp; 
    }
  });
}
var obj = new GFG_Fun(); 
obj.temp;
obj.temp = 100; // Error here
</script>

chevron_right


Output:

TypeError: Cannot set property temp of 
#<GFG_Fun> which has only a getter

Example 2: In this example, the getter method is defined for the object ‘Person’. Property ‘Age’can not be accessed directly.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
"use strict";
function Person(ageP) { 
  var age = ageP; 
  Object.defineProperty(this, 'age', { 
    get: function() {
      return age; 
    }
  });
}
var p = new Person(22);
p.age = 30;  // TypeError
</script>

chevron_right


Output:

TypeError: Cannot set property age of 
#<Person> which has only a getter

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.