Private Fields in Javascript

1–2 minutes

read

Advertisements

What are private fields?

Private fields are basically private variables that can not be accessed easily. To access these variables one need to access through the private data functions. Deep diving in javascript’s context, these are added to the JavaScript language through the TC39 proposal process, as part of the class fields proposal, which is at Stage 4 in the TC39 process. 

How to declare private fields?

To declare a private field we need to use hash ‘#’ in front of the variable name.

class A {
  #x = 10;
}

By this declaration, the variable x can not be accessed outside the class. Lets go through an example:

class A {
  b = 5; // public variable
  #c = 9; // private variable
}

var a = new A();
console.log("first: ", a.b); // 5
console.log("second: ", a.#c); // Uncaught SyntaxError

var a = new A() will create a new instance of the class A through which variables can be accessed.

a.#c can not be accessed because it’s a private instance and so can not be accessed like this. To access this, we have to create a function inside the class which can access this private variable.

class A {
  b = 5; // public variable
  #c = 9; // private variable
  
  g(){
  	return this.#c;
  }
}

var a = new A();
console.log("first: ", a.b); // 5
console.log("second: ",a.g()) //9

The function g() can access the private variable using this.#c after which the value can be accessed by calling the function. a.g().

Leave a comment