Private Fields, Getters & Static

Protect your internal data with private fields, control access with getters, and attach utilities directly to the class itself.

JavaScript7 min readConcept 24 of 62

Private Fields (#)

By default, all properties inside a JavaScript class are public, meaning anyone can access and change them.

By prefixing a property name with a hash (#), you create a **private field**. Private fields can only be read or modified from inside the class's own methods. If outside code tries to touch them, JavaScript throws a syntax error.

Getters and Setters

If you make a property private, you might still want outside code to read it, but not change it. Or, you might want to validate data before letting someone change it.

You can define get and set methods. To the outside world, these look exactly like normal properties (accessed without parentheses), but under the hood, they execute your custom logic.

Static Methods and Properties

Normally, methods are attached to the instances you create with new. But sometimes you want a utility function that belongs to the class itself.

By adding the static keyword before a method or property, you attach it directly to the class blueprint. You call them on the class itself, not on the instance (e.g., Math.random() or Array.isArray()).

Class Architecture

Analyze a User class that utilizes private fields for security, getters for safe access, and static properties for global tracking.

Class Architecture & Access Rules

class Vault {
// 1. Static (Lives on the class itself)
static globalCode = 999;
// 2. Private Field (Strictly internal)
#balance = 5000;
// 3. Getter (Public safe access)
get funds() {
return this.#balance;
}
}
const v = new Vault();
Access Matrix
Static
Vault.globalCode
✓ OKReturns 999. Static members live on the Class, not the instance.
Getter
v.funds
✓ OKReturns 5000. Accessed like a property, but runs the method!
Private
v.#balance
✗ ERRORSyntaxError! Private fields are physically blocked from outside access.
iA getter provides a safe, read-only window into the private #balance, completely protecting the data from malicious writes!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens if you try to access a private field like `user.#password` from outside the class?
  2. 2How do you invoke a getter method named `get fullName()`?
  3. 3Which of the following is true about `static` methods?

Remember this

  • Prefix a field with # to make it strictly private to the class.
  • get and set methods allow you to execute logic when a property is accessed or changed.
  • Getters and setters are accessed like normal properties (no parentheses).
  • static methods belong to the class itself, not the instances.
  • Static methods are great for utility functions or tracking data across all instances.

Done with this concept?

Mark it complete to track your progress. No login needed.