DEV Community

Cover image for 🎉🎉 Private Variables & Methods in JavaScript
Ashvin Kumar Suthar
Ashvin Kumar Suthar

Posted on

🎉🎉 Private Variables & Methods in JavaScript

Recently, a new proposal was introduced that would introduce private variables and methods to classes. Currently, it is at stage-3.

Its very simple, just put # before the name of variables or method, and it becomes private.

class Person {
  #salary = 100;

  #increaseSalary() {
    this.#salary += 1000;
  }
}

let p1 = new Person();

console.log(p1.#salary); //Error - Private name #salary is not defined
console.log(p1.#increaseSalary); //Error - Private name #increaseSalary is not defined
Enter fullscreen mode Exit fullscreen mode

👉 Live Demo/Playground

👉 Babel supports this feature in 7.2+ versions out of box.

👉 You can also enable this feature by just installing these babel plugins -
babel-plugin-proposal-private-methods
babel-plugin-proposal-class-properties

Top comments (0)