Private class fields in JavaScript, this time in true sense!

Private class fields in JavaScript, this time in true sense!

In general, one should ignore reading this further as, we are talking about yet another way to make a class field Private in JavaScript! We, the JS Developer community know more than couple of ways to do it already.

Be it,

  • Using Class Constructor
  • Using Closure
  • Keeping private data in WeakMaps
  • Using convention with underscore(_)
  • ... and very recently, Using ES6 Symbols

With any of the methods listed above, nothing really comes as a direct offering from JavaScript Language. Some of these methodologies are not making the fields truly private, well, until now.

Meet the Private fields in JavaScript

As part of the new class fields proposal, we are going to have the ability to declare a class field as Truly Private.

The Private fields can be enforced with the # as prefix to the variable intended to be Private. See the code block below:

class Counter {
  #count = 0

  increment() {
    this.#count++
  }
}

In above code, we have declared a class Counter with a private field count. You can actually run it on Latest Chrome(version # 72) or NodeJs(Version # 12).

Try accessing the count variable as:

new Counter().#count
  • You will not be able to access it.
  • Only way to access the private field is using the methods that might expose those.

No Backdoor to Access Private

This is the part amazed me and I have a great feeling of, JavaScript started behaving like other normal programming languages.

As quoted by the specification, here are the bundles of Joy!

Private fields provide a strong encapsulation boundary: It's impossible to access the private field from outside of the class, unless there is some explicit code to expose it (for example, providing a getter). This differs from JavaScript properties, which support various kinds of reflection and metaprogramming, and is instead analogous to mechanisms like closures and WeakMap, which don't provide access to their internals.

Got Questions about it?

Yeah, you must have some questions about it by now. Basic question I had was,

  • Why not a private keyword? Isn't that more normal than # prefix?

Well, they thought about it and please read this to gain more knowledge on it.

Let us welcome private to our life.

Please Share/Like if this information was useful to you. The Cover Picture credit goes to, Dayne Topkin on Unsplash