JS Accessors

Accessors (Getters and Setters)

In JavaScript, accessors are tools that allow you to retrieve or set the values of object properties. Accessors make working with objects easier and help control how values are read from or written to those objects.

An accessor is a special method in JavaScript that either gets a value from an object or sets a new value to an object. You can think of them like getters and setters.

  Getter: Used to retrieve a value from an object.

 Setter: Used to set or change a value in an object.

These methods help you manage how the values are read or updated in your object, giving you better control over the data.

How Accessors Work: The Getter and Setter

Let’s start with an example to explain both getter and setter.

Why Use Accessors?

  Control Over Data: Accessors help you control how properties are accessed or modified. You can ensure that the data stays correct, or even change the data format as it is retrieved.

•  Encapsulation: Accessors provide a way to keep internal details hidden while still allowing external code to interact with the object in a controlled way.

  Validation: You can use setters to validate the data before allowing changes (e.g., checking if an age is a positive number).

Example: Object with Getter and Setter

<body>
<script>
let person = {
firstName: “Saad”, // Property
lastName: “Shaikh”, // Property
age: 20, // Property
// Getter: Retrieves full name
get fullName() {
return this.firstName + ” ” + this.lastName;
},
// Setter: Changes age
set newAge(age) {
if (age < 0) {
console.log(“Age cannot be negative.”);
} else {
this.age = age; // Sets the new age
}
}
};
console.log(person.fullName); // “Saad Shaikh” (uses getter)
person.newAge = 25; // Uses setter to change age
console.log(person.age); // 25 (age is updated)
</script>
</body>

Code Explanation:

1. Object Declaration:

let person = {
firstName: “Saad”, // Property
lastName: “Shaikh”, // Property
age: 20, // Property

•  You are creating an object person with three properties:

•  firstName: The person’s first name, set to “Saad”.
  lastName: The person’s last name, set to “Shaikh”.
  age: The person’s age, set to 20.

2. Getter Method (fullName):

// Getter: Retrieves full name
get fullName() {
return this.firstName + ” ” + this.lastName;
},

  get fullName() is a getter method.
  It is used to retrieve the full name of the person. When you access person.fullName, it automatically calls this getter method.
  The getter concatenates the firstName and lastName properties and returns them as a single string (“Saad Shaikh”).
•  Key Point: When you call person.fullName, you don’t need to add parentheses because it’s a getter (not a regular function).

So, when you use:

console.log(person.fullName); // Output: “Saad Shaikh”

3. Setter Method (newAge):

// Setter: Changes age
set newAge(age) {
if (age < 0) {
console.log(“Age cannot be negative.”);
} else {
this.age = age; // Sets the new age
}
}

  set newAge(age) is a setter method.
  This setter allows you to modify the age property of the person object. However, before changing the age, the setter validates whether the new value is a positive number.
•  If the value of age is less than 0 (i.e., negative), it prints the message “Age cannot be negative.”.
  If the value is valid (i.e., non-negative), it updates the age property of the person object.

When you execute:

person.newAge = 25; // Uses setter to change age

  The setter newAge is triggered, and it sets the age property to 25 since 25 is a valid (positive) number.
  After that, if you check the age property of the person object, you’ll see that it has been updated to 25.

4. Accessing the Updated age Property:

console.log(person.age); // Output: 25 (age is updated)

This will output the updated age of the person object, which is now 25, as it was changed using the setter.

5. What Happens When You Try to Set a Negative Age?

If you try to set a negative age using the setter, this is what happens:

person.newAge = -5; // Invalid age

If you try to set a negative age using the setter, this is what happens:

Negative-Age
Output:
Negative-Age-Output

Course Video

Frequently Asked Questions

Still have a question?

Let's talk

JavaScript accessors are methods (get and set) used to dynamically access and modify object properties. Learn more in our JavaScript accessors free course video.

A getter (get) allows you to define a method to retrieve the value of a property.
Example:

let person = { 

  get fullName() { 

    return `${this.firstName} ${this.lastName}`; 

  } 

}; 

Explore this concept in the Learn JS accessors with free video tutorial.

A setter (set) allows you to define a method to set the value of a property.
Example:

let person = { 

  set fullName(name) { 

    [this.firstName, this.lastName] = name.split(” “); 

  } 

}; 

Check out practical examples in the Free JavaScript accessors tutorial for beginners.

Yes, you can define both getter and setter for the same property to enhance flexibility.
Example:

let person = { 

  get fullName() { return `${this.firstName} ${this.lastName}`; }, 

  set fullName(name) { [this.firstName, this.lastName] = name.split(” “); } 

}; 

Find detailed explanations in the JavaScript accessors with free tutorial.

Getters and setters encapsulate property access, abstracting logic behind properties to make code more readable and maintainable. Learn more in the JavaScript accessors free course video.

 

Yes, you can define getters and setters for computed properties.
Example:

let property = “name”; 

let obj = { 

  get [property]() { return this._name; }, 

  set [property](value) { this._name = value; } 

}; 

Discover how this works in the Learn JS accessors with free video tutorial.

No, by default, getters and setters are not enumerable, which means they do not appear in for…in loops. Learn more in our Free JavaScript accessors tutorial for beginners.

Accessors are not replacements for traditional methods but offer a more natural syntax for property-like access. This is explained in the JavaScript accessors with free tutorial.

 

Accessors might have a slight performance cost compared to direct property access, but the benefits in code clarity usually outweigh this cost. Check this out in the JavaScript accessors free course video.

Use the get and set keywords inside a class.
Example:

class Person { 

  get fullName() { return `${this.firstName} ${this.lastName}`; } 

  set fullName(name) { [this.firstName, this.lastName] = name.split(” “); } 

Watch this demonstrated in the Learn JS accessors with free video tutorial.