Property getters and setters in JavaScript
Nov 09, 2020 08:42 0 Comments Javascript PARTH

    Property getters and setters in JavaScript

 

They are essentially functions, that execute on getting and setting a value, but look like regular properties to an external code.

Getters and setters

Accessor properties are represented by “getter” and “setter” methods. In an object literal they are denoted by get and set:

let obj = {

  get propName() {

    // getter, the code executed on getting obj.propName

  },

  set propName(value) {

    // setter, the code executed on setting obj.propName = value

  }

};

The getter works when obj.propName is read, the setter – when it is assigned.

For instance, we have a user object with name and surname:

let user = {

  name: "John",

  surname: "Smith"

};

Now we want to add a full Name property, that should be "John Smith". Of course, we don’t want to copy-paste existing information, so we can implement it as an accessor:

let user = {

  name: "John",

  surname: "Smith",

  get fullName() {

    return `${this.name} ${this.surname}`;

  }

};

alert(user.fullName); // John Smith

From the outside, an accessor property looks like a regular one. That’s the idea of accessor properties. We don’t call user.fullName as a function, we read it normally: the getter runs behind the scenes.

As of now, fullName has only a getter. If we attempt to assign user.fullName=, there will be an error:

let user = {

  get fullName() {

    return `...`;

  }

};

user.fullName = "Test"; // Error (property has only a getter)

Let’s fix it by adding a setter for user.fullName:

let user = {

  name: "John",

  surname: "Smith",

  get fullName() {

    return `${this.name} ${this.surname}`;

  },

  set fullName(value) {

    [this.name, this.surname] = value.split(" ");

  }

};

// set fullName is executed with the given value.

user.fullName = "Alice Cooper";

alert(user.name); // Alice

alert(user.surname); // Cooper

As the result, we have a “virtual” property fullName. It is readable and writable.

 

Prev Next
About the Author
Topic Replies (0)
Leave a Reply
Guest User

You might also like

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let's Connect