Private and Public Fields

Expert-Level Explanation

In JavaScript classes, fields can be either private or public. Public fields can be accessed and modified from outside the class. Private fields, denoted by a #, can only be accessed or modified from within the class.

Creative Explanation

Think of public fields like public parks, accessible to everyone, and private fields like your private garden at home, accessible only to you and your family. In a class, private fields are kept hidden from the outside, providing a secure internal state.

Practical Explanation with Code

class Person {
    #age; // private field
    constructor(name, age) {
        this.name = name; // public field
        this.#age = age;
    }
    displayInfo() {
        console.log(`Name: ${this.name}, Age: ${this.#age}`);
    }
}

let person = new Person("Alice", 30);
person.displayInfo(); // Name: Alice, Age: 30
// person.#age; // Error: Private field '#age' must be declared in an enclosing class

Real-world Example

In a company, public fields are like general information available to all employees, such as the company's address. Private fields are like confidential employee records, accessible only by the HR department.