Accessors

ryanrackemann.developer's avatar
Published Aug 26, 2023Updated Jun 30, 2024
Contribute to Docs

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;
}
}
const person = new User('eddy', '[email protected]');
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:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn JavaScript on Codecademy