JavaScript #private

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

Fields and methods starting with # are private to the class body. Outside code cannot read or write them—even on the same object.

JavaScript Syntax

JavaScript
class Wallet {
  #balance = 0;
  deposit(n) { this.#balance += n; }
  getBalance() { return this.#balance; }
}
const w = new Wallet();
w.deposit(10);
console.log(w.getBalance());
Try it Editor

How It Works

  1. Private state. #balance is hidden.
  2. Public API. getBalance reads it safely.

Examples

Example 1 — Outside access throws

Syntax/runtime barrier.

JavaScript
class A { #x = 1; }
const a = new A();
try { console.log(a.#x); } catch (e) { console.log("blocked"); }
Try it Editor

How It Works

  1. Cannot access #x outside class (parse/runtime).

Example 2 — Private methods

#helper() stays internal.

JavaScript
class A { #h(){ return 1; } out(){ return this.#h(); } }
console.log(new A().out());
Try it Editor

How It Works

  1. Public method calls private helper.

Example 3 — Per-class privacy

Each class has its own # names.

JavaScript
console.log("private to declaring class");
Try it Editor

How It Works

  1. Not the same as _underscore convention.

Frequently Asked Questions

No. Underscore is only a naming habit. # is enforced by the language.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful