Private Fields, Getters & Static
Protect your internal data with private fields, control access with getters, and attach utilities directly to the class itself.
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
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Prefix a field with
#to make it strictly private to the class. getandsetmethods allow you to execute logic when a property is accessed or changed.- Getters and setters are accessed like normal properties (no parentheses).
staticmethods 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.