Es11 features- private class variables

ES6 introduced classes to make it reusable modules, Everything declared in class can be accessed by other modules.Prior to ES20, variables are declared in clousure to make it private With Es2020,Private class variables are introduced to allow the variables used in the class only.

Variables are added hash symbole to make it private use in a class. Syntax


Let’s see an example declaring private variable in class

class HelloWorld {
  #message = "How are you?";

const hello = new HelloWorld()
hello.getMessage() // How are you?

Declared private class variable message with hash symbole to it

accessing the private fields with object of the same class

Directling accessing the private variable throws Uncaught SyntaxError: Private field '#

console.log(greeting.#message) // Private name #message returns undefined