DEV Community

Cover image for πŸŽ‰πŸŽ‰ Private Variables & Methods in JavaScript
Ashvin Kumar Suthar
Ashvin Kumar Suthar

Posted on

3 5

πŸŽ‰πŸŽ‰ 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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay