What is the use of get and set in javascript?


JavaScript Accessors (Getters and Setters)

ECMAScript 5 (ES5 2009) introduced Getter and Setters.

Getters and setters allow you to define Object Accessors (Computed Properties).


JavaScript Getter (The get Keyword)

This example uses a lang property to get the value of the language property.

Example

// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  language: "en",
  get lang() {
    return this.language;
  }
};

// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;

Try it Yourself »


JavaScript Setter (The set Keyword)

This example uses a lang property to set the value of the language property.

Example

const person = {
  firstName: "John",
  lastName: "Doe",
  language: "",
  set lang(lang) {
    this.language = lang;
  }
};

// Set an object property using a setter:
person.lang = "en";

// Display data from the object:
document.getElementById("demo").innerHTML = person.language;

Try it Yourself »



JavaScript Function or Getter?

What is the differences between these two examples?

Example 1

const person = {
  firstName: "John",
  lastName: "Doe",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

// Display data from the object using a method:
document.getElementById("demo").innerHTML = person.fullName();

Try it Yourself »

Example 2

const person = {
  firstName: "John",
  lastName: "Doe",
  get fullName() {
    return this.firstName + " " + this.lastName;
  }
};

// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.fullName;

Try it Yourself »

Example 1 access fullName as a function: person.fullName().

Example 2 access fullName as a property: person.fullName.

The second example provides a simpler syntax.


Data Quality

JavaScript can secure better data quality when using getters and setters.

Using the lang property, in this example, returns the value of the language property in upper case:

Example

// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  language: "en",
  get lang() {
    return this.language.toUpperCase();
  }
};

// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;

Try it Yourself »

Using the lang property, in this example, stores an upper case value in the language property:

Example

const person = {
  firstName: "John",
  lastName: "Doe",
  language: "",
  set lang(lang) {
    this.language = lang.toUpperCase();
  }
};

// Set an object property using a setter:
person.lang = "en";

// Display data from the object:
document.getElementById("demo").innerHTML = person.language;

Try it Yourself »


Why Using Getters and Setters?

  • It gives simpler syntax
  • It allows equal syntax for properties and methods
  • It can secure better data quality
  • It is useful for doing things behind-the-scenes

Object.defineProperty()

The Object.defineProperty() method can also be used to add Getters and Setters:

A Counter Example

// Define object
const obj = {counter : 0};

// Define setters and getters
Object.defineProperty(obj, "reset", {
  get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
  get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
  get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
  set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
  set : function (value) {this.counter -= value;}
});

// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;

Try it Yourself »



The get syntax binds an object property to a function that will be called when that property is looked up.

Try it

Syntax

{ get prop() { /* … */ } }
{ get [expression]() { /* … */ } }

Parameters

prop

The name of the property to bind to the given function.

expression

You can also use expressions for a computed property name to bind to the given function.

Description

Sometimes it is desirable to allow access to a property that returns a dynamically computed value, or you may want to reflect the status of an internal variable without requiring the use of explicit method calls. In JavaScript, this can be accomplished with the use of a getter.

It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value, although it is possible to use a getter and a setter in conjunction to create a type of pseudo-property.

Note the following when working with the get syntax:

  • It can have an identifier which is either a number or a string;
  • It must have exactly zero parameters (see Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments for more information);
  • It must not appear in an object literal with another get e.g. the following is forbidden

    {
      get x() { }, get x() { }
    }
    

  • It must not appear with a data entry for the same property e.g. the following is forbidden

    {
      x: /* … */, get x() { /* … */ }
    }
    

Examples

Defining a getter on new objects in object initializers

This will create a pseudo-property latest for object obj, which will return the last array item in log.

const obj = {
  log: ['example','test'],
  get latest() {
    if (this.log.length === 0) return undefined;
    return this.log[this.log.length - 1];
  }
}
console.log(obj.latest); // "test"

Note that attempting to assign a value to latest will not change it.

Deleting a getter using the delete operator

If you want to remove the getter, you can just delete it:

Defining a getter on existing objects using defineProperty

To append a getter to an existing object later at any time, use Object.defineProperty().

const o = {a: 0};

Object.defineProperty(o, 'b', { get() { return this.a + 1; } });

console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)

Using a computed property name

const expr = 'foo';

const obj = {
  get [expr]() { return 'bar'; }
};

console.log(obj.foo); // "bar"

Defining static getters

class MyConstants {
  static get foo() {
    return 'foo';
  }
}

console.log(MyConstants.foo); // 'foo'
MyConstants.foo = 'bar';
console.log(MyConstants.foo); // 'foo', a static getter's value cannot be changed

Smart / self-overwriting / lazy getters

Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed. If it is never needed, you never pay the cost.

An additional optimization technique to lazify or delay the calculation of a property value and cache it for later access are smart (or memoized) getters. The value is calculated the first time the getter is called, and is then cached so subsequent accesses return the cached value without recalculating it. This is useful in the following situations:

  • If the calculation of a property value is expensive (takes much RAM or CPU time, spawns worker threads, retrieves remote file, etc.).
  • If the value isn't needed just now. It will be used later, or in some case it's not used at all.
  • If it's used, it will be accessed several times, and there is no need to re-calculate that value will never be changed or shouldn't be re-calculated.

Note: This means that you shouldn't write a lazy getter for a property whose value you expect to change, because if the getter is lazy then it will not recalculate the value.

Note that getters are not "lazy" or "memoized" by nature; you must implement this technique if you desire this behavior.

In the following example, the object has a getter as its own property. On getting the property, the property is removed from the object and re-added, but implicitly as a data property this time. Finally, the value gets returned.

const obj = {
  get notifier() {
    delete this.notifier;
    return this.notifier = document.getElementById('bookmarked-notification-anchor');
  },
}

get vs. defineProperty

While using the get keyword and Object.defineProperty() have similar results, there is a subtle difference between the two when used on classes.

When using get the property will be defined on the instance's prototype, while using Object.defineProperty() the property will be defined on the instance it is applied to.

class Example {
  get hello() {
    return 'world';
  }
}

const obj = new Example();
console.log(obj.hello);
// "world"

console.log(Object.getOwnPropertyDescriptor(obj, 'hello'));
// undefined

console.log(
  Object.getOwnPropertyDescriptor(
    Object.getPrototypeOf(obj), 'hello'
  )
);
// { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined }

Specifications

Specification
ECMAScript Language Specification
# sec-method-definitions

Browser compatibility

BCD tables only load in the browser

See also

What is the difference between Get and set in JavaScript?

Getters and setters allow us to define Object Accessors. The difference between them is that the former is used to get the property from the object whereas the latter is used to set a property in an object.

Why we need get and set?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

What are classes What are getters and setters in JavaScript?

In a JavaScript class, getters and setters are used to get or set the properties values. “get” is the keyword utilized to define a getter method for retrieving the property value, whereas “set” defines a setter method for changing the value of a specific property.

Why use get set in TypeScript?

The same get and set are also available in TypeScript as it is from the same company - Microsoft. What is Get and Set? Get and Set are known as "auto properties" which are used to access the class variable. It helps you to execute the logic when accessing the variable.