This page looks best with JavaScript enabled

Private Variables in Javascript Class

 ·   ·  ☕ 2 min read

We define a class and its variables like so -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class UserData {
  name = "";
  type = "";
  internalUserFlag = false;
  constructor({ name, type }) {
    this.name = name;
    this.type = type;
  }
}

const student1 = new UserData({ name: "Neo" });
console.log("student1: ", student1); // UserData { name: '', type: '', internalUserFlag: false }

See quickly get started with Javascript classes if you want to know more.

We can potentially extend the class and have multiple validation rules. We also like to keep variables like type and internalUserFlag private. These variables can be changed by extension classes, but not by external methods.

Earlier, there was no good way of enforcing this. As a convention people would prefix private variables with ‘_’. But it would be available to all and sundry anyway.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class UserData {
  name = "";
  _type = "";
  _internalUserFlag = false;
  constructor({ name, _type }) {
    this.name = name;
    this._type = _type;
  }
}

const student1 = new UserData({ name: "Neo", _type: "Programmer" });
console.log("type", student1._type); // type:  Programmer

You could potentially have functions within functions and manage abstractions, but it was not quite considered a clean way.

With the class fields proposal, we have entered the era of better abstraction in Javascript classes.

You can now just prefix variable with a # to declare it as private.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class UserData {
  name = "";
  #type = "internal";

  constructor({ name }) {
    this.name = name;
  }

  setType(type) {
    // will be set by admin / internally
    this.#type = type;
    console.log("#type set: ", this.#type); // secret programmer
  }
}

const student1 = new UserData({ name: "Neo" });
student1.setType("secret programmer"); // assume admin is initiating this function!

console.log("type: ", student1.#type);
// cannot access this will cause error
// SyntaxError: Undefined private field #type: must be declared in an enclosing class

Not satisfied with the class support? Switch to Typescript!

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things