DEV Community


Posted on

What is Private field in JS (JavaScript)

In JavaScript, the term "private field" typically refers to a concept related to encapsulation and access control in object-oriented programming. JavaScript traditionally lacked native support for private members in classes, but with the introduction of ECMAScript 2015 (ES6) and subsequent versions, private fields and methods became possible.

in easy language, In JavaScript, a "private field" is like having a secret inside a special box. Imagine you have a box, and you want to keep something hidden inside it so that others can't mess with it. That hidden thing is a private field.

Private fields are used to encapsulate data within a class, making it accessible only from within that class. They are declared using the # symbol as a prefix to the field name. Here's a simple example:

class MyClass {

  constructor(value) {
    this.#privateField = value;

  getPrivateField() {
    return this.#privateField;

  setPrivateField(newValue) {
    this.#privateField = newValue;

const myObject = new MyClass(42);

console.log(myObject.getPrivateField()); // Output: 42
console.log(myObject.getPrivateField()); // Output: 99
console.log(myObject.#privateField); // Error: Private field '#privateField' must be declared in an enclosing class
Enter fullscreen mode Exit fullscreen mode

In this example, #privateField is a private field of the MyClass class. It can only be accessed or modified from within the class methods. If you try to access it directly from outside the class, an error will occur.

Private fields help in achieving encapsulation, which is an important principle in object-oriented programming. Encapsulation involves bundling the data (fields) and methods (functions) that operate on the data within a single unit, i.e., a class. This helps in hiding the internal details of the class and exposing only the necessary functionalities.

It's worth noting that private fields are a feature of modern JavaScript, and older browsers or environments may not support them. Always consider the target environment when using language features introduced in newer specifications.

Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and Typescript, as well as contribute to open-source projects and learning Typescript. I am currently seeking a remote job or internship.




Top comments (0)