Course contentsShow
← JavaScript
Lesson 662 of 2,72316. Object Methods and PatternsFree lesson

Storing Data in Private Properties

Learn the convention of using underscore-prefixed properties to store actual data behind getters and setters.

Storing Data in Private Properties

What you'll learn: How to use underscore-prefixed property names to store the actual data that getters and setters control.

The Problem with Direct Access

When you create a getter and setter, you need somewhere to actually store the value. You can't store it in a property with the same name as the getter/setter—that would create infinite recursion. The getter would try to access itself forever!

The Convention: Underscore Prefix

JavaScript developers use a simple naming convention: prefix the property name with an underscore (_) to indicate it's "private" data meant to be accessed only through getters and setters.

const user = {
  _age: 25,  // "Private" storage property
  
  get age() {
    return this._age;
  },
  
  set age(value) {
    if (value >= 0) {
      this._age = value;
    }
  }
};

console.log(user.age);  // 25 (uses getter)
user.age = 30;          // Uses setter
console.log(user.age);  // 30

Important: It's a Convention, Not Enforcement

The underscore doesn't technically make the property private. You can still access user._age directly. The underscore is a signal to other developers: "Don't touch this directly—use the getter/setter instead."

// You CAN do this (but shouldn't):
user._age = -5;
console.log(user.age);  // -5 (bypasses validation!)

This convention works on trust—it tells you "this property is implementation detail."

Key Takeaway: Use underscore-prefixed properties (_propertyName) to store the actual data behind getters and setters, signaling that direct access should be avoided.