Introduction And Learning Goals

Hello! Today's journey ventures into the cornerstone of JavaScript's object-oriented fundamentals: Encapsulation. This concept establishes a protective barrier around an object's data, keeping it untouched by the external code ecosystem. Let's take a closer look:

  1. The importance of encapsulation: Delivering robust, versatile, and intuitive code.
  2. Private Data: How JavaScript protects certain data from external access.
  3. Getters and Setters: These are the tools that control data access and modification for the protection and abstraction of data.
Why Encapsulation?

Encapsulation fulfills a threefold role: it maintains integrity, controls data modification, and provides data abstraction — interfaces accessible to users. Think about using a cell phone — you interact with an interface without meddling with its circuits. Following this same logic, encapsulation safeguards the internal implementation while exposing safe interfaces.

Private Data In JavaScript

Now, let's talk about Private Data: In modern JavaScript, we create private properties by prefixing the variable name with a hash symbol (#). Unlike regular properties, these cannot be accessed or modified from outside the class. Let's illustrate this with a Car class, introducing a private attribute, #speed:

class Car {
    #speed = 0; // private speed attribute

    constructor() {
        // The #speed property is only accessible inside this class
    }
}

A Note on Conventions: You may encounter older code using an underscore (_speed) to denote private data. This was a "gentleman's agreement" among developers to stay away from that data. However, the modern # notation is strictly enforced by the JavaScript engine itself.

Using Getters And Setters

Getters and Setters are gatekeepers controlling access to private data. In our Car class, a getter function retrieves the #speed attribute. In contrast, a setter function modifies it as follows:

class Car {
    #speed = 0; // Initialize private speed as 0

    get speed() { // Get current speed
        return this.#speed;
    }

    set speed(value) { // Update speed
        // Speed should stay in the range 0 to 150
        if (value < 0) {
            this.#speed = 0;
        } else if (value > 150) {
            this.#speed = 150;
        } else {
            this.#speed = value;
        }
    }
}

These methods allow us to retrieve or set the car's speed safely while the actual #speed variable remains hidden.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal