Skip to content Skip to sidebar Skip to footer

In Javascript, What Happens If I Assign To An Object Property That Has A Getter But No Setter?

In the following code, both uses of console.log(o.x) print 1. What happens to the assignment o.x = 2? Is it just ignored? var o = { get x() { return 1; } } console

Solution 1:

In sloppy mode, yes, it'll just be ignored - the value "assigned" will be discarded. But in strict mode (which is recommended), the following error will be thrown:

Uncaught TypeError: Cannot set property x of #<Object> which has only a getter

'use strict';
var o = {
    getx() {
        return1;
    }
}

console.log(o.x);  // 1
o.x = 2

Post a Comment for "In Javascript, What Happens If I Assign To An Object Property That Has A Getter But No Setter?"