JavaScript Accessors
In JavaScript, object properties can be obtained using accessors. Properties are established and retrieved with methods known as “getters” and “setters”.
The get keyword is used to define a getter method for establishing a custom behavior when accessing the values of object properties, while the set keyword is used to create a setter method that determines the behavior when assigning values to those properties.
Syntax
There are two ways to access properties: dot notation and bracket notation.
const object = {
get propertyName() {}
}
object.propertyName
object[propertyName]
Example
The following example defines a User class with a constructor and a getter method. It demonstrates how to encapsulate and access the email information of a user using accessor methods.
class User {constructor(name, email) {this._name = name;this._email = email;}get userEmail() {return this._email;}}console.log(person.userEmail);
This example results in the following output:
Codebyte Example
Here is a codebyte example that demonstrates the dot and bracket notation of property accessors:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours