Getter and Setter in JavaScript
Learn via video course
Overview
The Javascript Object Accessors are used to access and manipulate object properties i.e. the values associated with the javascript objects. The getter and setter methods in Javascript are primarily used as object accessors. The getter and setter in javascript are used to alter the property values.
Scope of the Article
In this article we will learn:
- How to access the properties of the javascript objects.
- The internal attributes of javascript objects and how do their values affect our output.
- The difference between regular functions and object accessors in javascript.
Accessor Descriptors
Imagine you're supposed to make ID cards for 100 students of a branch. All these cards will have the same fields i.e. name, class, rollNo, etc. Each ID card will have a different value for these fields.
If we were about to do the above task using Object-Oriented Programming, then the "Card" could be a class and the individual IDs could be its objects. Now the question is, "How do we assign values to these fields? Or How do we access these fields?" In javascript, we've been provided accessor descriptors (discussed later in this section) that are used to assign or access the values of these fields.
A Property Descriptor is a simple JavaScript object associated with each property of the object that contains information about that property such as its value and other meta-data. Property Descriptors present in objects come in two main flavors: data descriptors and Accessor Descriptors. A data descriptor is a property that has a value, which may or may not be writable.
The Accessor Descriptors in Javascript are properties described by a pair of getter-setter functions. The accessor properties do not have value and are not writable, but instead, they have to get and set functions.
Note: Accessor descriptors are objects
An Accessor Descriptor may have:
- get: It is a function without arguments. The Javascript getter methods are used to access the properties of an object.
- set: a function with one argument. The Javascript setter methods are used to change the values of an object.
- enumerable: It defines properties that can be viewed if it is iterated using the for…in loop or an Object.
- configurable: It controls whether a property can be deleted from the object or whether its attributes can be changed.
JavaScript Getter (The get Keyword)
The Javascript get syntax binds an object property to a function that will be called when that property is looked up.
In layman's terms, the Javascript getter provides us a way to define an Object’s property. The Javascript getter methods are mainly used to access the properties of an object.
Note: The object's property's value does not get calculated until it is accessed.
Syntax
- prop: It is the name of the property that is used to bind to the provided function.
- expression: We can also use expressions for a computed property name to bind to the given function. It is an ES6 addition.
Example
JavaScript Setter (The set Keyword)
The set syntax binds an object property to a function to be called when there is an attempt to set that property.
The Javascript set executes whenever a particular property is altered. Generally, the Setters in javascript is used in correspondence with getters to create a type of pseudo-property. The Javascript setter methods are used to change the values of an object.
Syntax
- prop: The name of the property to bind to the given function.
- val: An alias for the variable that holds the value attempted to be assigned to prop.
- expression: From ECMAScript 2015 onwards, we can also use expressions for a computed property name to bind to the given function.
Example
Enumerable
A JavaScript object is basically an unordered list of key-value pairs. Thus for..in loops are generally used to access the properties of the objects.
The enumerable attribute in javascript is used to determine if a property is accessible when the object’s properties are enumerated by the for...in loop.
Note: By default, all object properties created by initializer or assignment are enumerated.
Example
Output:
Explanation of the example
In the above example, the properties firstName, lastName are created by the initializer and the property age is created by assignment. Thus all three will be enumerable and therefore will be accessible to the key in the for...in loop.
How to change the enumerable attribute of a property?
The internal enumerable attribute of a property can be changed by using the Object.defineProperty() method.
Note: the Object.defineProperty() has been discussed in detail in furthur section.
Example
Output:
Explanation of the example
In the above example, the object definition is similar to that of the previous one but in this example, the 'lastName' property is created with the enumerable flag sets to false, therefore it does not show up in the for...in loop.
Configurable
The configurable attribute in javascript can modify the behavior of the object's properties. It can make them non-enumerable, non-writable, or even non-configurable. Configurable properties are the only ones that can be removed using the delete operator. By default its value is true.
The Javascript object's properties can be deleted or modified only if the configurable attribute for the object is true, otherwise, we cannot alter the attributes of the object.
Example
Output:
Explanation of the example:
In the above example, the configurable attribute of the 'lastName' is set to false, thus upon using the delete keyword on the property it would return an error.
Function vs Getters
The prime difference between the function and getters is that in the function call we are accessing the function whereas, in the getter call, we are accessing the property. Thus the getter syntax turns out simpler and more readable than the function.
Example
Accessing object attribute using function:
Output:
Accessing object attribute using getter:
Output:
Explanation of the example:
In the above example, we have created an object Student with properties like firstName, lastName, rollNo. Now in the 'displayName method' and 'displayName getter' are respectively used to access the name of the student. We can observe that the 'displayName method' is returning player.myFunc() which is a function whereas 'displayName getter' is returning player.myFunc which can be used as a property.
Data Quality While Using Getters and Setters
The Getters and Setters are used to secure better data quality. The getter and setter methods in javascript provide centralized control of how a certain field is initialized and provided to the user, thus making it easier to verify and debug.
Example
Output
Object.defineProperty() in JavaScript
The Object.defineProperty() method in javascript is used to define a new property directly on an object. The Object.defineProperty() returns an object. It is generally used to change the flags of the attributes.
syntax
- Obj: It is the Object on which the property is defined.
- Prop: It is the name of a property to be defined or modified.
- Descriptor: It is the descriptor for the property being defined or modified.
Example
Output:
Explanation of the example
In the above example, we are defining a new property ' city' using Object.defineProperty whose value is set to be ' California. Thus upon assigning the property using ' student.city' the object will be assigned the property.
Reasons to Use Getters and Setters
- Accessor and Mutator methods encapsulate our classes, keeping them safe by hiding unnecessary implementation details and only modifying certain values.
- Get and Set methods to have a slightly simpler syntax and also allow us to recognize their purpose at a glance.
- The syntax for getters and setters is similar to that of the javascript method thus it is easy to learn.
Smarter Getters/Setters
Getter and setter in Javascript can be used as wrappers over “real” property values. This is done to gain more control over operations with them using which we could add constraints etc.
For example, we can restrict users from keeping too short names for the name property in the above-discussed example.
Example
Output:
Explanation of the example:
In the above example, we have wrapped the setter with a constrain that if the length of the value passed to it is less than 4 then it prompts an alert. Thus when the user.name is assigned 'p' it alerts the message. user.name = "Peter" works fine as its length is greater than 4.
Note:
Technically, external code is able to access the name directly by using user.name. But there is a widely known convention that properties starting with an underscore "" are internal and should not be touched from outside the object.
Using for Compatibility
The Getter and Setter in Javascript can be used to allow to take control over a “regular” data property at any moment. It is done by replacing the regular data property with a getter and a setter and altering its behavior.
Example
Let's suppose that we are creating User objects with name and age properties.
But for some reason, we have decided to use birthday instead of age.
Now, what do we do of the age property that would have been used in the earlier code chunks? The naive method would be to replace all occurrences of age with birthday. But this would take a lot of time.
Adding a getter solves this issue. The age is now calculated from the current date.
Output:
Browser Support
Browser | Chrome | Firefox | Opera | Safari | Edge |
---|---|---|---|---|---|
Version | yes | yes | yes | yes | 9.0 |
- The first column contains names of web browsers and the rows contain the versions that support getters and setters.
- The version mentioned in the row is the minimum version required to run the program.
- If the row has yes then the getter and setter are supported by all versions of the browser.
Conclusion
- The Javascript Object Accessors are used to access the properties of objects.
- The getter and setter in Javascript are used to access and manipulate the object properties.
- Accessor and Mutator methods encapsulate our classes, keeping them safe by hiding unnecessary implementation details and only modifying certain values.
- The Enumerable Attribute in Javascript is used to determine if a property is accessible when the object’s properties are enumerated by the for...in loop.
- The Javascript object's properties can be deleted or modified only if the configurable attribute for the object is true, otherwise, we cannot alter the attributes of the object.
- The Object.defineProperty() method in Javascript is used to define a new property directly on an object.
- The Getter and Setter in javascript can be used to allow to take control over a regular data property