Course contentsShow
← JavaScript
Lesson 1829 of 2,72338. Object-Oriented PatternsFree lesson

Convention-Based Privacy with Underscore Prefix

Using _privateName as a social contract to signal internal properties not meant for external use.

Convention-Based Privacy with Underscore Prefix

You'll learn how JavaScript developers use the underscore prefix (_) as a social signal to mark properties as "private" or internal, even though JavaScript doesn't enforce this privacy.

The Core Idea

JavaScript objects expose all their properties by default. Since true privacy requires special techniques (closures, WeakMaps, or newer private fields), developers adopted a simple naming convention: prefix internal properties with an underscore (_).

This is a social contract, not a technical barrier. The underscore says: "Hey, I'm internal. Don't touch me from outside this object."

How It Works

class User {
  constructor(name, password) {
    this.name = name;
    this._password = password; // "Private" by convention
  }

  authenticate(input) {
    return input === this._password;
  }
}

const user = new User('Alice', 'secret123');
console.log(user.name);           // 'Alice' - public, use freely
console.log(user._password);      // 'secret123' - works, but breaks the contract!
console.log(user.authenticate('secret123')); // true - proper usage

The underscore doesn't prevent access—it's a warning label. Respectful code doesn't directly read or modify _password.

Why Use This Convention?

  • Clear communication: Signals which properties are stable public API vs implementation details
  • Documentation: Tells other developers (and future you) what's safe to rely on
  • Refactoring freedom: You can change _password internally without worrying about breaking external code
  • Lightweight: No performance cost or complex patterns needed

Think of it like a "Staff Only" door—technically unlocked, but you're expected not to go through it.

Key Takeaway:
The underscore prefix (_privateName) is a widely-adopted convention that signals "internal use only," relying on developer discipline rather than language enforcement to maintain encapsulation.