Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

What happens when you assign to a getter-only property?

Do you know what will be the output of this code?

JavaScript
class Account {
  #balance = 100;
  get balance() {
    return this.#balance;
  }
}

const acc = new Account();
acc.balance = 500;
console.log(acc.balance);
Show answer and explanation

The answer is 100.

balance has a getter but no setter, so the assignment has no effect. In strict mode (like ES modules) it throws a TypeError instead. #balance is a private field that can’t be reached from outside.

Take the full quiz Next question →

More Classes & Prototypes questions

  1. Why does this become undefined when you extract a method?
  2. What happens when a constructor returns an object?
  3. Do objects see prototype changes made after they're created?
  4. Are JavaScript classes hoisted?
  5. Can you call a static method on a class instance?

Related topics