Back to JavaScript Notes
Topic #405

Getters and Setters

By the end, you can define JavaScript getters and setters so an object exposes computed properties that run functions when read or assigned.

What it is

A getter is a function that runs when you read a property. A setter is a function that runs when you assign to a property. Together they create an accessor property: it looks like ordinary data from the outside, but the value is computed, validated, or stored internally when accessed.

The mental model is “property syntax, method behavior.” Related terms include accessor property, computed value, data property, and Object.defineProperty.

Why it matters

  • Validate input before storing it, such as rejecting negative ages.
  • Derive values from other fields, such as building fullName from first and last.
  • Hide internal state while keeping a clean public API.
  • Trigger side effects, such as logging, caching, or recalculating totals.
  • Make objects easier to use because callers do not need to remember method names.

Syntax or steps

  1. Inside an object literal, write get propertyName() for reading.
  2. Return the value you want the property to expose.
  3. Write set propertyName(value) for assignment.
  4. Use this to read or update related properties.
  5. Access the property normally: obj.prop calls the getter, obj.prop = x calls the setter.
const obj = {
  get propName() {
    return "computed value";
  },
  set propName(value) {
    // store or validate value
  }
};

Example

const person = {
  first: "Ada",
  last: "Lovelace",
  get fullName() {
    return `${this.first} ${this.last}`;
  },
  set fullName(name) {
    const [first, last] = name.split(" ");
    this.first = first;
    this.last = last;
  }
};

console.log(person.fullName);
person.fullName = "Grace Hopper";
console.log(person.first, person.last);
  • fullName is not stored as a normal property; it is computed from first and last.
  • Reading person.fullName calls the getter and returns "Ada Lovelace".
  • Assigning person.fullName = "Grace Hopper" calls the setter.
  • The setter splits the string and updates the underlying fields.
  • The final log prints Grace Hopper.

Common mistakes

  • Forgetting return in a getter. The property becomes undefined.
  • Naming the getter or setter the same as the backing field, causing recursion. Use a different internal name, such as _first, or a private field in a class.
  • Writing a setter with no parameter. The setter needs the assigned value, for example set age(value).
  • Detaching the method from the object. If you copy the getter to another variable, this may no longer point to the original object.

When to use it

Use getters and setters when the value feels like a property. Use ordinary methods when the operation feels like an action or needs multiple arguments.

NeedUseWhy
Read a derived valuegetterCallers can use obj.fullName instead of obj.getFullName().
Validate or transform assignmentsetterCallers can use obj.age = 30 while the object controls storage.
Perform an actionmethodNames like save() or reset() are clearer than property syntax.
Define accessors dynamicallyObject.definePropertyUseful when property names are generated at runtime.

Practice

Guided exercise: create an object named temp with a celsius property and a getter named fahrenheit that returns celsius * 9 / 5 + 32.

const temp = {
  celsius: 20,
  get fahrenheit() {
    return this.celsius * 9 / 5 + 32;
  }
};

console.log(temp.fahrenheit);

Expected output: 68.

Challenge: add a setter named fahrenheit that converts a Fahrenheit value back to Celsius and stores it in celsius. Hint: use (value - 32) * 5 / 9.

Quick check

Question: What happens if a getter and setter use the same property name as the field they try to store?

Answer: They can call themselves recursively, often causing a stack overflow. Use a different backing field name or a private field.

Summary

Getters and setters let JavaScript objects expose computed or controlled properties using normal property syntax. They are best for derived values and validation, while methods remain better for actions and multi-argument operations.

Want to go beyond the notes?

Join Coding Now Tech Institute's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Getters and Setters – FAQs

Quick answers about learning Getters and Setters in JavaScript.

This free note from Coding Now Tech Institute explains Getters and Setters in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on Coding Now Tech Institute, including Getters and Setters, is 100% free with no signup required.
With focused practice, most students grasp Getters and Setters in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now