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)