JavaScript 2022 - New Features - Part 3

ECMAScript 2022(ES13) : New Capabilities

Private Mutator

A property can be made private using # symbol. The property name has to be prefixed with #.


class MyClass {
    #privateField; // Private field

    constructor() {
      this.#privateField = 42; // Initialize private field
    }

    get privateValue() {
      return this.#privateField; // Getter method
    }

    set #privateValue(newValue) { // private setter
      this.#privateField = newValue; // Setter method
    }
  }

  const instance = new MyClass();
  console.log(instance.privateValue); // Access the private property using the getter
  //instance.privateValue = 100; // Error

In the above code the setter has been made private i.e it is only accessible within the class and cannot be accessed outside the class. The accessor (get) can also be made private.

Computed Static Field Initialization

The static computed field can also be initialized inside the class.

// static computed field
let desc="Description";

class Test {
    static [desc]="DB connection";  // initialized
};
console.log(Test.Description); // DB connection

In above code the static computed field is initialized in the class and accessed outside the class using the class name.

Using in keyword with private field

The in keyword can be used with private field to verify if the given field exists.

// using in operator can check if the private property is there 
// on the object
class Myclass2 {
   #i=10;
   static #j;
   show() {
    console.log(#i in this, #j in Myclass2);
   }
};

let obj = new Myclass2();
obj.show(); // true true

In the above code private field and static private field are checked if they exists on MyClass2 object. Since both the fields are present the output is true.

Complete Code Listing


class MyClass {
    #privateField; // Private field

    constructor() {
      this.#privateField = 42; // Initialize private property
    }

    get privateValue() {
      return this.#privateField; // Getter method
    }

    set #privateValue(newValue) { // private setter
      this.#privateField = newValue; // Setter method
    }
  }

  const instance = new MyClass();
  console.log(instance.privateValue); // Access the private property using the getter
  //instance.privateValue = 100; // Error

  // static computed field
let desc="Description";

class Test {
    static [desc]="DB connection";  // initialized
};
console.log(Test.Description); // DB connection

// using in operator can check if the private property is there 
// on the object
class Myclass2 {
    #i=10;
    static #j;
    show() {
     console.log(#i in this, #j in Myclass2);
    }
 };

 let obj = new Myclass2();
 obj.show(); // true true

Did you find this article valuable?

Support Programming with Mahavir by becoming a sponsor. Any amount is appreciated!