Open In App

What Are Access Modifiers In JavaScript ?

Last Updated : 20 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Access modifiers in JavaScript play a significant role in controlling the visibility and accessibility of class members. Although JavaScript is not traditionally an object-oriented programming (OOP) language, the introduction of classes and access modifiers in ECMAScript 6 (ES6) allowed developers to implement OOP principles into their applications.

Access modifiers in JavaScript are a crucial aspect of the language that allows developers to control the visibility and availability of variables and functions in their code. These modifiers determine whether certain elements can be accessed or modified from different parts of the program. JavaScript provides three main access modifiers: private, public, and protected, each of which serves a specific purpose in terms of encapsulating and hiding information.

Types of Access Modifiers

  • Public (default)
  • Private
  • Protected

Purpose of Access Modifiers

  • The main purpose of access modifiers is to control and restrict access to members of a class. This encapsulation ensures data integrity, and security and helps adhere to the principle of least privilege.
  • Access modifiers also improve code maintainability and collaboration between team members. By explicitly defining who can access and modify class members, you minimize unexpected side effects and improve code clarity.

Public Access Modifier

Members marked as public can be accessed from anywhere. Public members are the default in JavaScript classes. They are accessible in and out of the classroom. For example, methods marked as public can be called from anywhere in your code.

Example:

Javascript




class Person {
    constructor(name) {
        this.name = name; // Public member
    }
  
    introduce() {
        console.log(`Hello, my name is ${this.name}.`);
    }
}
  
const person = new Person('Alice');
person.introduce(); // Accessing a public method
console.log(person.name); // Accessing a public property


Output

Hello, my name is Alice.
Alice

Explanation: In the public access modifier example, a Person class is defined with a public member called name. Public members are directly accessible outside the class. The introduce method allows for the public property name to be accessed and displayed. An instance of the Person class is created, and both public methods and properties are accessed, demonstrating the concept of public access.

Private Access Modifier

Members marked as private are only accessible within the class itself. Private members are marked with the # symbol. These members are only accessible from within the class itself. They are invisible to external code. Private members provide encapsulation and ensure that the internals of a class remain hidden.

Example:

Javascript




Javascript
  
class Person {
    #name; // Private member
  
    constructor(name) {
        this.#name = name;
    }
  
    #sayHello() {
        console.log(`Hello, my name is ${this.#name}.`);
    }
  
    introduce() {
        // Accessing a private method
        this.#sayHello();
    }
}
  
const person = new Person('Bob');
// Accessing a public method that 
// accesses a private method
person.introduce();
  
// Error: Private member is not accessible
console.log(person.#name);


Output:

pvt

Explanation: In the private access modifier example, a Person class is defined with a private member #name. Private members are indicated by the # symbol and are not accessible from outside the class. The class also contains a private method #sayHello, which is invoked within the introduce method. Attempting to access the private property #name from outside the class results in an error, illustrating the private access modifier.

Protected Access Modifier

Members marked as protected are accessible within the class and its subclasses. Members marked as protected are accessible within the class and its subclasses. You can use the protected keyword to define protected members. These members maintain a level of encapsulation while allowing access to subclasses.

Example:

Javascript




class Vehicle {
    constructor(speed) {
        if (this.constructor === Vehicle) {
            throw new Error("Abstract classes cannot be instantiated.");
        }
        this.speed = speed;
    }
}
  
class Car extends Vehicle {
    constructor(speed) {
        super(speed);
    }
    getSpeed() {
        // Accessing the protected member in a subclas
        return this.speed; s
    }
}
  
const myCar = new Car(60);
// Outputs: 60
console.log(myCar.getSpeed());


Output:

protected

Explanation: In the protected access modifier example, a Vehicle class is defined with a protected member speed. Although JavaScript does not natively support protected access, the code simulates this behavior. The Car class extends Vehicle and can access the protected member speed within the getSpeed method. An instance of Car is created, and the protected member is accessed, showcasing the protected access modifier’s concept. The code also includes error handling to prevent the instantiation of abstract classes.

Conclusion: Access modifiers in JavaScript are essential to maintain data integrity, security, and code clarity in your applications. By controlling the visibility and availability of class members, you can effectively encapsulate data and behavior. Whether you use public, private, or protected access modifiers, they contribute to well-structured and maintainable code and improve your development process and collaboration with other team members.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads