DEV Community

Cover image for JavaScript getters and setters
Amitav Mishra
Amitav Mishra

Posted on • Originally published at jscurious.com

JavaScript getters and setters

The getters and setters are helpful to access object properties and manipulate them in an encapsulated way. Let’s explore these methods in detail.

Getter

The get keyword is used to create a getter function that will return a computed value. Unlike normal functions, we don’t need to call the getter function; instead, we can access it directly with its name.

const person = {
  first_name: 'Peter',
  last_name: 'Parker',
  get full_name() {
      return `${this.first_name} ${this.last_name}`
  }
}

console.log(person.full_name); // Peter Parker

Enter fullscreen mode Exit fullscreen mode

The get keyword binds the getter function with an object property of the same name. When we access this object property, the getter function result gets returned.

Just remember, until and unless we access the object property, its value never gets calculated. That means it won’t execute the getter function and assign the returned value to the object property beforehand.

Things to remember while creating getters

  • It should not have any parameters.
  • There should not be another data property or getter with the same name present.

Like data properties, we can also delete getters.

const obj = {
  get data() {
      return 'jscurious';
  }
}
delete obj.data;
console.log(obj.data); // undefined
Enter fullscreen mode Exit fullscreen mode

Setter

The set keyword is used to create a setter function. The set keyword binds the setter function with an object property of the same name. So, whenever we try to change the value of this object property, the setter function gets executed.

const obj = {
  msg: '',
  set message(value) {
    this.msg = value;
  }
}
obj.message = 'Hello';
console.log(obj.msg); // Hello
Enter fullscreen mode Exit fullscreen mode

Things to remember while creating setters

  • It should exactly have one parameter.
  • There should not be another data property or setter with the same name present. But both getter and setter can have the same name.

Like data properties, we can also delete setters.

const obj = {
  msg: '',
  set message(value) {
    this.msg = value;
  }
}
delete obj.message;
Enter fullscreen mode Exit fullscreen mode

Using getter and setter inside class

Let’s create one encapsulated class. The class will have one private field that can be accessed only through setter and getter.

class Square {
  #side_value;

  set side(value) {
    this.#side_value = value;
  }
  get side() {
    return this.#side_value;
  }
  get area() {
    return this.#side_value ** 2;
  }
}

const sq = new Square();
sq.side = 25;
console.log(sq.side); // 25
console.log(sq.area); // 625
Enter fullscreen mode Exit fullscreen mode

You may also like


Thanks for your time ❤️
Find more of my writings on web development blogs at jscurious.com

Top comments (0)