CodeBlanks Logo Icon CodeBlanks

Get and set

Learn getter and setter methods.

What are getters and setters?

The get and set keywords define an accessor for a property. The getter runs when reading the property, the setter runs when assigning to it. This lets you keep a private backing field and control access. A getter takes no parameter, a setter takes one.

class Account {
  private _balance = 0;
  get balance() { return this._balance; }
  set balance(v: number) { this._balance = v; }
}

Validation with a getter

You can validate the assigned value by putting a condition inside the setter. If an invalid value is assigned, an error is thrown or the value is ignored. This preserves internal consistency. The getter usually just returns the private field.

class User {
  private _age = 0;
  get age() { return this._age; }
  set age(v: number) {
    if (v < 0) throw new Error("negative age");
    this._age = v;
  }
}

Practice Sicaklik getter and setter

Define a Sicaklik class with a private _derece field starting at 0. get derece returns _derece. set derece(v: number) sets _derece to 0 if negative, otherwise to v. Add the lines const s = new Sicaklik(); s.derece = -5; console.log(s.derece);.

Starter code

index.ts
// Sicaklik sinifi tanimla
// private _derece = 0 olsun
// derece icin get ve set erisimcileri yaz
// negatif deger atandiginda 0 yap

// const s = new Sicaklik(); s.derece = -5; console.log(s.derece);

Sample solution

index.ts
class Sicaklik {
  private _derece = 0;
  get derece() { return this._derece; }
  set derece(v: number) { this._derece = v < 0 ? 0 : v; }
}
const s = new Sicaklik();
s.derece = -5;
console.log(s.derece);

Expected output

0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many parameters does a setter method take?

  • Two parameters
  • Takes no parameters
  • Any number of parameters
  • Exactly one parameter Correct answer

Explanation: A setter takes exactly one parameter to receive the value being assigned; a getter takes none.

2 Getter keyword

Question
class Kutu {
  private _icerik = 0;
  ____ icerik() { return this._icerik; }
}
Answer
class Kutu {
  private _icerik = 0;
  get icerik() { return this._icerik; }
}

Explanation: The accessor that runs when reading a property is defined with the `get` keyword.

3 Accessor parts

Term Meaning
get Reads the value
set Writes the value
özel alan Backing field
doğrulama Condition in setter

All lessons in Intermediate