JavaScript Getters, Setters, Private Fields and Private Methods (#)
Sometimes a property should be calculated when it is read (a cart’s total), checked when it is written (an email must contain @), or hidden from outside code completely (an API token). Getters, setters and private fields give classes exactly this control. In this lesson you will learn to write getters and setters, validate values, create read-only and computed properties, and keep internal state truly private with # fields and methods, the language features behind encapsulation.
📖 What You’ll Learn: getters with get, setters with set, computed and read-only properties, validation in setters, getters and setters in object literals, private fields with #, private methods, private static members, checking private membership with in, how private fields differ from the underscore convention and closures, and a secure API client example.
📤 Getters: Properties Computed on Read
Definition: a getter is a method that runs when a property is read. You define it with get name() { ... } and use it like a normal property, without parentheses.
📄 getter.js
class Cart {
items = [];
add(price, qty = 1) {
this.items.push({ price, qty });
return this;
}
get total() { // computed every time it is read
return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
get isEmpty() {
return this.items.length === 0;
}
}
const cart = new Cart();
console.log(cart.isEmpty, cart.total);
cart.add(10, 3).add(899);
console.log(cart.isEmpty, cart.total); // no () - it looks like a property
console.log(typeof cart.total);
⌨️ Terminal
node getter.js
🖥️ Output
true 0
false 929
number
A getter always returns the current value, so it never goes out of date the way a stored total property would if someone forgot to update it.
⚠️ Watch out: Calling a getter like a method fails: cart.total() throws TypeError: cart.total is not a function, because cart.total is already the number.
📥 Setters: Control What Is Written
Definition: a setter is a method that runs when a property is assigned, defined with set name(value) { ... }. It is the natural place to validate or normalise input. A setter usually stores the value in another (often private) property.
📄 setter.js
class User {
#email = ""; // private storage (explained below)
get email() {
return this.#email;
}
set email(value) {
const clean = String(value).trim().toLowerCase();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(clean)) {
throw new Error(`Invalid email: "${value}"`);
}
this.#email = clean;
}
}
const u = new User();
u.email = " Asha@SQATools.in "; // setter runs: trimmed and lower-cased
console.log(u.email);
try {
u.email = "not-an-email";
} catch (e) {
console.log(e.message);
}
console.log(u.email); // unchanged after the failed assignment
⌨️ Terminal
node setter.js
🖥️ Output
asha@sqatools.in
Invalid email: "not-an-email"
asha@sqatools.in
🔒 Read-Only and Derived Properties
A getter without a setter creates a read-only property. In strict code (ES modules, class bodies, "use strict" files) assigning to it throws; in sloppy scripts the assignment is silently ignored:
📄 readonly.js
"use strict"; // ES modules and test files are strict too
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
}
set fahrenheit(f) { // a setter can update the underlying value
this.celsius = (f - 32) * 5 / 9;
}
get kelvin() { // getter only: read-only
return this.celsius + 273.15;
}
}
const t = new Temperature(25);
console.log(t.fahrenheit, t.kelvin);
t.fahrenheit = 212;
console.log(t.celsius);
try {
t.kelvin = 0;
} catch (e) {
console.log(e.constructor.name + ":", e.message);
}
⌨️ Terminal
node readonly.js
🖥️ Output
77 298.15
100
TypeError: Cannot set property kelvin of #<Temperature> which has only a getter
Getters and setters live on the class prototype, so they do not appear in Object.keys or JSON.stringify of an instance. Add a toJSON() method if a computed value should be serialised.
📦 Getters and Setters in Object Literals
Getters and setters also work in plain objects, without a class:
📄 literal.js
const report = {
passed: 18,
failed: 2,
get total() {
return this.passed + this.failed;
},
get passRate() {
return `${((this.passed / this.total) * 100).toFixed(1)}%`;
},
set result(text) { // parse "17/20" into numbers
const [p, t] = text.split("/").map(Number);
this.passed = p;
this.failed = t - p;
},
};
console.log(report.total, report.passRate);
report.result = "17/20";
console.log(report.passed, report.failed, report.passRate);
⌨️ Terminal
node literal.js
🖥️ Output
20 90.0%
17 3 85.0%
🔐 Private Fields (#)
Definition: a private field is a class field whose name starts with #. It can only be accessed by code inside the class body. Outside code cannot read, write, list or even detect it; trying to access it is a syntax error. Private fields are enforced by the language (ES2022), not just by convention.
📄 private-fields.js
class ApiClient {
#token; // private
baseURL; // public
constructor(baseURL, token) {
this.baseURL = baseURL;
this.#token = token;
}
headers() {
return { authorization: `Bearer ${this.#token}` }; // inside the class: allowed
}
}
const client = new ApiClient("https://api.qa", "secret-123");
console.log(client.headers());
console.log(client.token, Object.keys(client), JSON.stringify(client));
console.log(client);
⌨️ Terminal
node private-fields.js
🖥️ Output
{ authorization: 'Bearer secret-123' }
undefined [ 'baseURL' ] {"baseURL":"https://api.qa"}
ApiClient { baseURL: 'https://api.qa' }
The token never appears in Object.keys, JSON output or the property list, which is exactly what you want for credentials that might end up in test logs. Accessing it from outside does not even compile:
📄 private-outside.js
class Secret {
#value = 42;
}
const s = new Secret();
console.log(s.#value);
⌨️ Terminal
node private-outside.js
🖥️ Output
/home/you/js-course/private-outside.js:5
console.log(s.#value);
^
SyntaxError: Private field '#value' must be declared in an enclosing class
Node.js v26.13.0
💡 Tip: Note: console.log(client) in Node.js does not print private fields, but Chrome DevTools does show them when you inspect an object. Privacy protects you from other code, not from someone debugging.
🛠️ Private Methods and Static Private Members
Methods, getters and static members can be private too. Private methods are perfect for internal helper steps that callers should not use directly:
📄 private-methods.js
class OrderService {
static #instances = 0; // private static field
#orders = [];
constructor() {
OrderService.#instances++;
}
static get instances() { // public read-only access to a private static
return OrderService.#instances;
}
#validate(order) { // private method
if (!order.id || order.total <= 0) throw new Error(`Invalid order: ${JSON.stringify(order)}`);
}
place(order) {
this.#validate(order);
this.#orders.push(order);
return this.#orders.length;
}
}
const svc = new OrderService();
new OrderService();
console.log(svc.place({ id: 1, total: 499 }), OrderService.instances);
try {
svc.place({ id: 2, total: 0 });
} catch (e) {
console.log(e.message);
}
console.log(typeof svc.validate, typeof svc["#validate"]);
⌨️ Terminal
node private-methods.js
🖥️ Output
1 2
Invalid order: {"id":2,"total":0}
undefined undefined
Checking for a private field with in
#field in obj (ES2022) checks whether an object has a given private field, which is a reliable way to test whether an object really is an instance of your class:
📄 private-in.js
class Token {
#value;
constructor(v) { this.#value = v; }
static isToken(obj) {
return #value in obj;
}
}
console.log(Token.isToken(new Token("x")), Token.isToken({ value: "x" }));
⌨️ Terminal
node private-in.js
🖥️ Output
true false
⚖️ # Fields vs _underscore vs Closures
| Technique | Truly private? | Notes |
|---|---|---|
this._token (underscore) | No: just a naming convention | Visible in keys, JSON and logs; anyone can change it |
| Closure variable in a factory function | Yes | Methods are recreated for each object |
this.#token (private field) | Yes, enforced by the language | Works with classes and inheritance; subclasses cannot access parent # fields |
📄 compare.js
class Legacy {
constructor() { this._password = "hunter2"; }
}
console.log(JSON.stringify(new Legacy())); // the "private" value leaks into JSON
class Modern {
#password = "hunter2";
check(p) { return p === this.#password; }
}
console.log(JSON.stringify(new Modern()), new Modern().check("hunter2"));
⌨️ Terminal
node compare.js
🖥️ Output
{"_password":"hunter2"}
{} true
⚠️ Watch out: Private fields are not inherited in the sense of being accessible: a subclass cannot read this.#parentField. If subclasses need access, expose a protected-style getter or method, or keep the value public.
🧪 Tester Scenario: A Safe, Validated Test Configuration
This configuration class validates every value on the way in, computes derived settings, and keeps the password private so it never appears in logs or reports:
📄 test-config.js
class TestConfig {
#password;
#retries = 0;
env;
constructor({ env, user, password, retries = 0 }) {
if (!["qa", "staging", "prod"].includes(env)) throw new Error(`Unknown env "${env}"`);
this.env = env;
this.user = user;
this.#password = password;
this.retries = retries; // goes through the setter
}
get baseURL() {
return this.env === "prod" ? "https://www.example.com" : `https://${this.env}.example.com`;
}
get retries() {
return this.#retries;
}
set retries(n) {
if (!Number.isInteger(n) || n < 0 || n > 3) throw new RangeError(`retries must be 0-3, got ${n}`);
this.#retries = n;
}
credentials() {
return { user: this.user, password: this.#password };
}
toJSON() { // what reports and logs will show
return { env: this.env, user: this.user, baseURL: this.baseURL, retries: this.retries, password: "***" };
}
}
const config = new TestConfig({ env: "staging", user: "qa_bot", password: "S3cret!", retries: 2 });
console.log(JSON.stringify(config));
console.log(config.credentials().password.length, "characters (used for login, never logged)");
for (const bad of [{ env: "dev" }, { env: "qa", retries: 9 }]) {
try {
new TestConfig(bad);
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
}
⌨️ Terminal
node test-config.js
🖥️ Output
{"env":"staging","user":"qa_bot","baseURL":"https://staging.example.com","retries":2,"password":"***"}
7 characters (used for login, never logged)
Error: Unknown env "dev"
RangeError: retries must be 0-3, got 9
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Write a class Circle with a radius property and getters area and diameter.
Show answer
📄 practice1.js
class Circle {
constructor(radius) { this.radius = radius; }
get area() { return +(Math.PI * this.radius ** 2).toFixed(2); }
get diameter() { return this.radius * 2; }
}
const c = new Circle(3);
console.log(c.area, c.diameter);🖥️ Output
28.27 6Q2. Add a setter age to a Person class that rejects values below 0 or above 150 with an error.
Show answer
📄 practice2.js
class Person {
#age = 0;
get age() { return this.#age; }
set age(v) {
if (!Number.isInteger(v) || v < 0 || v > 150) throw new RangeError(`Invalid age: ${v}`);
this.#age = v;
}
}
const p = new Person();
p.age = 29;
console.log(p.age);
try { p.age = -5; } catch (e) { console.log(e.message); }🖥️ Output
29
Invalid age: -5Q3. Create a Counter class with a private #count, methods increment() and a read-only getter value. Show that counter.value = 100 does not change it.
Show answer
📄 practice3.js
class Counter {
#count = 0;
increment() { this.#count++; return this; }
get value() { return this.#count; }
}
const c = new Counter().increment().increment();
try { c.value = 100; } catch (e) { console.log(e.constructor.name); }
console.log(c.value);🖥️ Output
2Q4. Write an object literal fullName helper with first, last, a getter full and a setter full that splits "Asha Rao" into first and last.
Show answer
📄 practice4.js
const person = {
first: "",
last: "",
get full() { return `${this.first} ${this.last}`.trim(); },
set full(text) { [this.first, this.last = ""] = text.split(" "); },
};
person.full = "Asha Rao";
console.log(person.first, "|", person.last, "|", person.full);🖥️ Output
Asha | Rao | Asha RaoQ5. Write a class Vault with a private method #encrypt(text) (reverse the text) and a public store(text) that returns the encrypted value. Show that #encrypt is not reachable from outside.
Show answer
📄 practice5.js
class Vault {
#encrypt(text) { return [...text].reverse().join(""); }
store(text) { return this.#encrypt(text); }
}
const v = new Vault();
console.log(v.store("secret"), typeof v.encrypt);🖥️ Output
terces undefinedQ6. Explain the output: why does the token not appear?
class Session {
#token = "abc";
user = "asha";
}
console.log(JSON.stringify(new Session()), Object.keys(new Session()));Show answer
📄 practice6.js
class Session {
#token = "abc";
user = "asha";
}
console.log(JSON.stringify(new Session()), Object.keys(new Session()));🖥️ Output
{"user":"asha"} [ 'user' ]Private fields are not normal properties: they are invisible to Object.keys, for...in and JSON.stringify. Only code inside the class can use them.
🧠 MCQ Quiz: Getters, Setters, Private Fields
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- How do you read a getter named total?Answer: obj.total. Getters are accessed like properties.
- When does a setter run?Answer: When the property is assigned. obj.email = “x” calls set email(“x”).
- What happens when you assign to a getter-only property inside strict code?Answer: TypeError. Class code is strict, so it throws.
- How do you declare a private field?Answer: #name inside the class body. The # is part of the name.
- What happens with
obj.#secretoutside the class?Answer: SyntaxError: the code does not compile. Private names are checked when the code is parsed. - Do private fields appear in JSON.stringify output?Answer: No. Use toJSON to control serialised output.
- Can a subclass access its parent’s #private field directly?Answer: No. Expose a getter or method if subclasses need it.
- What does
#field in objcheck?Answer: Whether obj has that private field (is a real instance). It is a brand check (ES2022). - What is the weakness of the _underscore convention?Answer: The property is still public and visible. It is only a hint to other developers.
- Why put validation in a setter?Answer: Every assignment is checked automatically. Invalid data is rejected at the point it enters the object.
💼 Interview Questions and Answers
Q1. What are getters and setters, and why use them?
Getters (get x()) and setters (set x(v)) are accessor methods that look like normal properties to callers. Getters compute values on read (totals, derived URLs, formatted names) so they are never stale; setters validate or normalise values on write. They let a class change its internal representation without changing its public API.
Q2. How do you create private members in JavaScript?
Modern classes use # private fields, methods, getters and static members, which the language enforces: they cannot be accessed or even detected from outside the class body. Before ES2022, privacy was emulated with closures (factory functions or module scope) or WeakMaps keyed by instance; the underscore prefix is only a convention and provides no protection.
Q3. What is encapsulation, and how do private fields support it?
Encapsulation means hiding an object’s internal state and exposing only a controlled interface. With # fields the state cannot be changed from outside, so every change goes through methods or setters that can enforce rules (validation, invariants, logging). It reduces coupling: callers depend on the public methods, not on how data is stored.
Q4. Predict the output.
📄 predict.js
class Box {
#items = [];
get size() { return this.#items.length; }
add(x) { this.#items.push(x); return this; }
}
const b = new Box().add(1).add(2);
b.size = 10;
console.log(b.size, Object.keys(b));
⌨️ Terminal
node predict.js
🖥️ Output
2 []
This file is not in strict mode outside the class, and assigning b.size = 10 happens outside the class body, so the assignment to a getter-only property is silently ignored. size still reports 2, and the instance has no own enumerable keys.
❓ Frequently Asked Questions
🤔 When should I use a getter instead of a method?
Use a getter for a cheap, side-effect-free value that feels like a property (cart.total, user.fullName). Use a method when the work is expensive, has side effects or needs arguments.
🤔 Are private fields supported everywhere?
Yes. Private fields and methods (ES2022) work in all current browsers and every supported Node.js version, and TypeScript supports them too.
🤔 What is the difference between TypeScript private and #private?
TypeScript’s private keyword is checked only at compile time and the property is public at runtime. #private is enforced by JavaScript itself at runtime.
🤔 Can getters be static?
Yes. static get name() defines a getter on the class itself, useful for read-only access to private static data.
🏁 Summary
- Getters (
get x()) compute values on read; setters (set x(v)) run on assignment and are ideal for validation. - A getter without a setter is read-only; accessors live on the prototype and are not serialised.
#fields and methods are truly private, enforced by the language and invisible to keys, JSON and outside code.- Static members can be private too, and
#field in objchecks for genuine instances. - Use private fields for secrets and internal state, exposing only safe getters, methods and
toJSONoutput.
Next, continue with Lesson 42: OOP Principles.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in