JavaScript Accessors

ArvindNexus'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.

  • 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

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

All contributors

Contribute to 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