JavaScript and TypeScript course ยท Module 3: Classes and OOP

Encapsulation and Private Fields (#)

6 min read ยท
In this lesson7

In our Jurassic Park, dinosaur data must be strictly protected. Not every employee should have direct access to DNA sequences or enclosure security codes. Encapsulation is a fundamental principle of object-oriented programming that allows us to hide internal implementation details and expose only a controlled interface. In JavaScript, from ES2022, we have true private fields denoted by the # symbol.

What is encapsulation?

Encapsulation is a principle based on hiding the internal state of an object and exposing it exclusively through defined methods. Thanks to this:

  • We protect data from unauthorized modification
  • We control access to internal properties
  • We can validate data before saving it
  • We simplify code maintenance - internal implementation can change without affecting the rest of the program

Private fields with

In JavaScript we declare private fields by adding # before the field name. Such a field is accessible exclusively inside the class where it was declared:

class Dinosaur {
  // Private fields - inaccessible from outside
  #dnaSequence;
  #healthStatus;
  #dangerLevel;

  // Public fields - accessible from outside
  species;
  name;

  constructor(species, name, dnaSequence, dangerLevel) {
    this.species = species;
    this.name = name;
    this.#dnaSequence = dnaSequence;
    this.#healthStatus = 100;
    this.#dangerLevel = dangerLevel;
  }

  // Public method - controlled access to data
  getStatus() {
    return `${this.name} (${this.species}): health ${this.#healthStatus}%, danger ${this.#dangerLevel}/5`;
  }
}

const rex = new Dinosaur("Tyrannosaurus Rex", "Rexy", "ATCG-GCTA-TTAA", 5);

console.log(rex.species);    // "Tyrannosaurus Rex" - public field
console.log(rex.name);       // "Rexy" - public field
console.log(rex.getStatus()); // Works - public method

// console.log(rex.#dnaSequence); // SyntaxError! Private field
// console.log(rex.#healthStatus); // SyntaxError! Private field

Attempting to access the #dnaSequence field from outside the class will cause a syntax error. This is true privacy - not just a convention.

Getters and setters - controlled access

To allow reading or modifying private fields, we use getters (get) and setters (set). A setter allows data validation before saving:

class DinosaurEnclosure {
  #maxCapacity;
  #currentDinosaurs;
  #securityCode;

  constructor(name, maxCapacity, securityCode) {
    this.name = name;
    this.#maxCapacity = maxCapacity;
    this.#currentDinosaurs = [];
    this.#securityCode = securityCode;
  }

  // Getter - read capacity
  get capacity() {
    return this.#maxCapacity;
  }

  // Getter - number of dinosaurs
  get dinosaurCount() {
    return this.#currentDinosaurs.length;
  }

  // Getter - list of names (a copy, not a reference!)
  get dinosaurs() {
    return [...this.#currentDinosaurs];
  }

  // Setter with validation
  set maxCapacity(value) {
    if (value < this.#currentDinosaurs.length) {
      throw new Error("Cannot reduce capacity below current number of dinosaurs!");
    }
    if (value <= 0) {
      throw new Error("Capacity must be greater than zero!");
    }
    this.#maxCapacity = value;
  }

  // Public method with validation
  addDinosaur(dinoName) {
    if (this.#currentDinosaurs.length >= this.#maxCapacity) {
      return `Enclosure ${this.name} is full! Maximum capacity: ${this.#maxCapacity}`;
    }
    this.#currentDinosaurs.push(dinoName);
    return `${dinoName} added to enclosure ${this.name}`;
  }

  // Method requiring authorization
  getSecurityCode(authToken) {
    if (authToken !== "PARK-ADMIN-2024") {
      return "No access! Administrator authorization required.";
    }
    return this.#securityCode;
  }
}

const enclosure = new DinosaurEnclosure("Raptor Pen", 4, "SEC-7742");

console.log(enclosure.name);          // "Raptor Pen"
console.log(enclosure.capacity);      // 4 - getter
console.log(enclosure.addDinosaur("Blue"));    // "Blue added..."
console.log(enclosure.addDinosaur("Charlie")); // "Charlie added..."
console.log(enclosure.dinosaurCount); // 2

// Getter returns a copy - modification doesn't affect the original
const dinos = enclosure.dinosaurs;
dinos.push("Hacker-Dino");
console.log(enclosure.dinosaurCount); // Still 2!

// Validation in setter
enclosure.maxCapacity = 6; // OK
// enclosure.maxCapacity = 0; // Error! Capacity must be > 0

// Access control for sensitive data
console.log(enclosure.getSecurityCode("wrong-token"));     // "No access!"
console.log(enclosure.getSecurityCode("PARK-ADMIN-2024")); // "SEC-7742"

Private methods

Just like fields, methods can also be private. Private methods serve as internal helper mechanisms of the class:

class DNAAnalyzer {
  #samples;
  #analysisLog;

  constructor() {
    this.#samples = [];
    this.#analysisLog = [];
  }

  // Private method - sample validation
  #validateSample(sample) {
    const validBases = ["A", "T", "C", "G"];
    return sample.split("").every(base => validBases.includes(base));
  }

  // Private method - operation logging
  #log(message) {
    this.#analysisLog.push({
      timestamp: new Date().toISOString(),
      message
    });
  }

  // Public method using private ones
  addSample(species, dnaSequence) {
    if (!this.#validateSample(dnaSequence)) {
      this.#log(`Rejected DNA sample for ${species}: invalid sequence`);
      return "Error: Invalid DNA sequence!";
    }

    this.#samples.push({ species, dna: dnaSequence });
    this.#log(`Added DNA sample for ${species}`);
    return `DNA sample for ${species} registered successfully`;
  }

  // Public access to results
  getSampleCount() {
    return this.#samples.length;
  }

  getLog() {
    return [...this.#analysisLog]; // Copy of the log
  }
}

const analyzer = new DNAAnalyzer();
console.log(analyzer.addSample("T-Rex", "ATCGATCG"));    // Registered
console.log(analyzer.addSample("Raptor", "ATCGXYZ"));     // Error!
console.log(analyzer.getSampleCount()); // 1
console.log(analyzer.getLog());         // Operation history

// analyzer.#validateSample("ATCG"); // SyntaxError! Private method

Why is encapsulation important?

Imagine that without encapsulation someone could directly modify the state of the park's security system:

// WITHOUT encapsulation - dangerous!
class UnsafePark {
  fences = true;
  electricPower = true;
  dinosaurCount = 15;
}

const park = new UnsafePark();
park.fences = false;       // Someone turned off the fences!
park.dinosaurCount = -5;   // Nonsensical value
// No validation, no control - catastrophe!

// WITH ENCAPSULATION - safe!
class SafePark {
  #fencesActive;
  #electricPower;
  #dinosaurCount;

  constructor(dinoCount) {
    this.#fencesActive = true;
    this.#electricPower = true;
    this.#dinosaurCount = dinoCount;
  }

  deactivateFences(authCode) {
    if (authCode !== "EMERGENCY-OVERRIDE") {
      return "Denied! Disabling fences requires an emergency code.";
    }
    this.#fencesActive = false;
    return "WARNING: Fences deactivated!";
  }

  get status() {
    return {
      fences: this.#fencesActive ? "ACTIVE" : "INACTIVE",
      power: this.#electricPower ? "ON" : "OFF",
      dinosaurs: this.#dinosaurCount
    };
  }
}

const safePark = new SafePark(15);
console.log(safePark.deactivateFences("wrong")); // Denied!
console.log(safePark.status); // Everything safe

Encapsulation in inheritance

Important note: private fields with # are not accessible in child classes. If a child class needs access to the parent's data, the parent must expose it through public methods or getters:

class Animal {
  #name;
  #health;

  constructor(name, health) {
    this.#name = name;
    this.#health = health;
  }

  // Getter exposes value to child classes
  get name() {
    return this.#name;
  }

  get health() {
    return this.#health;
  }

  // Protected method (convention _) allowing modification of health
  _setHealth(value) {
    if (value < 0) value = 0;
    if (value > 100) value = 100;
    this.#health = value;
  }
}

class ParkDinosaur extends Animal {
  #species;

  constructor(name, species, health) {
    super(name, health);
    this.#species = species;
  }

  feed() {
    // Using public getters and parent methods
    const newHealth = Math.min(this.health + 10, 100);
    this._setHealth(newHealth);
    return `${this.name} (${this.#species}) fed. Health: ${this.health}%`;
  }
}

const dino = new ParkDinosaur("Rexy", "T-Rex", 70);
console.log(dino.feed()); // "Rexy (T-Rex) fed. Health: 80%"

Summary

Encapsulation with private fields # is a powerful tool that allows:

  1. Hiding implementation - internal fields and methods are inaccessible from outside
  2. Data validation - setters can check correctness before saving
  3. Access control - sensitive operations require authorization
  4. Safe getters - returning copies instead of references to internal data
  5. Private methods - helper functions hidden from the class user

In Jurassic Park, encapsulation protects our systems just as fences protect visitors from dinosaurs - controlled, secure access instead of chaos.

Code for this lesson: index.js
// Encapsulation and private fields - Jurassic Park
console.log("=== Encapsulation in Jurassic Park ===\n");

// 1. Class with private fields
class Dinosaur {
  #dnaSequence;
  #healthStatus;

  constructor(name, species, dna) {
    this.name = name;
    this.species = species;
    this.#dnaSequence = dna;
    this.#healthStatus = 100;
  }

  // Getter - controlled read
  get health() {
    return this.#healthStatus;
  }

  // Setter with validation
  set health(value) {
    if (value < 0 || value > 100) {
      console.log("Error: health must be 0-100!");
      return;
    }
    this.#healthStatus = value;
  }

  // Public method
  getStatus() {
    return this.name + " (" + this.species + "): " + this.#healthStatus + "%";
  }

  // Controlled access to DNA
  getDNA(authCode) {
    if (authCode !== "LAB-ACCESS") {
      return "No access to DNA!";
    }
    return this.#dnaSequence;
  }
}

const rex = new Dinosaur("Rexy", "T-Rex", "ATCGATCG");

console.log("--- Public fields ---");
console.log("Name:", rex.name);
console.log("Species:", rex.species);

console.log("\n--- Getter/Setter ---");
console.log("Health:", rex.health);
rex.health = 85;
console.log("After change:", rex.health);
rex.health = 150; // Validation!

console.log("\n--- Access control ---");
console.log(rex.getDNA("wrong"));
console.log(rex.getDNA("LAB-ACCESS"));

console.log("\n--- Status ---");
console.log(rex.getStatus());

// 2. Class with private methods
class Enclosure {
  #dinosaurs;
  #maxCapacity;

  constructor(name, capacity) {
    this.name = name;
    this.#maxCapacity = capacity;
    this.#dinosaurs = [];
  }

  // Private method
  #validateAdd(dino) {
    return this.#dinosaurs.length < this.#maxCapacity;
  }

  addDinosaur(dino) {
    if (!this.#validateAdd(dino)) {
      return this.name + " is full!";
    }
    this.#dinosaurs.push(dino);
    return dino + " added to " + this.name;
  }

  get count() {
    return this.#dinosaurs.length;
  }

  // Returns a copy, not a reference!
  get dinosaurs() {
    return [...this.#dinosaurs];
  }
}

console.log("\n--- Private methods ---");
const pen = new Enclosure("Raptor Pen", 3);
console.log(pen.addDinosaur("Blue"));
console.log(pen.addDinosaur("Charlie"));
console.log(pen.addDinosaur("Delta"));
console.log(pen.addDinosaur("Echo")); // Full!
console.log("Dinosaurs:", pen.dinosaurs);
console.log("Count:", pen.count);

// Attempt to modify the copy
const list = pen.dinosaurs;
list.push("Hacker");
console.log("After hacking attempt:", pen.count); // Still 3!

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do you mark a private field in a JavaScript class (ES2022)?

Hands-on tasks in the game

  • Code editor

    Create a class with private fields and controlled data access

  • Horizontal ordering

    Arrange the elements that define a getter in a class:

  • Horizontal ordering

    Arrange the elements for creating a class instance with parameters:

  1. QuestionPrivate Fields in Classes
  2. Coding taskEncapsulation - Practice
  3. Put in orderGetter and Setter in a Class
  4. Put in orderCreating a Class Instance

Useful articles