JavaScript

How to Define Private Methods in JavaScript

The idea behind using private methods is straightforward. When you want to keep something private, whether a method or a property, in this scenario, you can define private methods or private properties, which are utilized to hide the inner functionality of a class from the other classes. In a JavaScript class, you can add private fields, private instance methods, private static methods, and private getters and setters.

This write-up will explain the procedure to define Private Methods in JavaScript. So, let’s start!

Private methods in JavaScript

The type of methods that cannot be accessed outside of the class where it is defined or by the base class is known are Private methods. These methods are utilized to secure the sensitive information stored in class fields such as personal information or passwords.

In a JavaScript class, to declare something as “private,” which can be a method, property, or getter and setter, you have to prefix its name with the hash character “#”.

Syntax of Private instance method

class NewClass {
  #privateMethod() {
    // body of privateMethod
  }
}

In the above-given syntax, the private instance method is “#privateMethod”, which can be only invoked within “NewClass” and you cannot access it in the subclass of “NewClass” or from outside.

this” keyword is used for calling the “#privateMethod()” inside of the created “NewClass”:

this.#privateMethod();

Private Static Methods in JavaScript

Private static methods are loaded in the memory before you create an instance of that specific class and they are independent of class instantiation.

Syntax for defining a private static method

In a JavaScript program, to define a private static method, you have to use the keyword “static” before adding the method name with the “#” character:

class NewClass {
  static #privateStaticMethod() {
    // body of the privateStaticMethod
  }
}

Now, to invoke the created static private method, we will specify the class name “NewClass” instead of using “this” keyword:

NewClass.#privateStaticMethod();

Private Getters and Setters in JavaScript

In JavaScript, private getters and setters are used for retrieving and setting the private fields of a class. 

Syntax for defining private getters and setters

In JavaScript, “get” and “set” keywords are utilized for creating getters and setters for the private fields:

class NewClass {
  #firstField;
  get #field() {
      return #firstField;
  }
  set #field(value){
      #firstField = value;
  }
}

How to define Private Methods in JavaScript

The private methods in JavaScript can keep your data private. It is preferred to define all class methods as “private” by default. After that, if an object needs to interact with other class objects, you can turn it to a “public” method.

Example: How to define Private Methods in JavaScript
First of all, we will create an “Employee” class having two private fields: “#name” and “#designation”. After doing so, we will add a constructor:

class Employee {
  #name;
  #designation;
  constructor(name, designation) {
    this.#name = name;
    this.#designation = designation;
  }

Next, we will define the private methods “#employeeName()” and “ #employeeDesignation()” for getting the values of the added private fields:

#employeeName() {
    return `${this.#name}`;
  }
#employeeDesignation() {
    return `${this.#designation}`;
 }

A “showInfo()” public function is also added in our Employee class which will invoke the following private methods:

showInfo(format = true){
console.log(this.#employeeName(), this.#employeeDesignation()); }
}

After setting up the Employee class, we will create an “employee” object while passing “Alex” and “Manager” as the values of the “name” and “designation” fields:

let employee = new Employee('Alex', 'Manager');

Lastly, we will invoke the “showInfo()” method by utilizing the employee object:

employee.showInfo();

Execution of the above-given program will display the private field values of “employee” object in the console:

Example: How to define Private Static Methods in JavaScript
We will add a “#verify()” private static method in the Employee with “name” parameter. The “#verify()” method will check if the length of “name” is greater than or equal to “4“; otherwise, it will throw an exception stating that “The entered name must be a string having at least 4 characters”.

The mentioned static private method will be added in the Employee Class constructor so that it can validate the “name” argument before assigning it to the corresponding attribute:

class Employee {
#name;
#designation;
  constructor(name, designation) {
    this.#name = Employee.#verify(name);
    this.#designation = designation;}
    static #verify(name) {
      if (typeof name === 'string') {
        let str = name.trim();
        if (str.length === 4) {
          return str;
        }
      }
      throw 'The entered name must be a string having at least 4 characters';
    }
  #employeeName() {
    return `${this.#name}`;
  }

  #employeeDesignation() {
    return `${this.#designation}`;
  }
showInfo(format = true){
console.log(this.#employeeName(), this.#employeeDesignation()); }
}

In the first case, we will create an “employee” object and pass a name which will meet the added condition in the #verify() static private method:

let employee = new Employee('Alex', 'Manager');
employee.showInfo();

After validating the #name field, it can be easily fetched by the showInfo() method:

For the second time, we will specify a name which comprises three characters:

let employee = new Employee('Sia', 'Manager');
employee.showInfo();

You can see from the below-given output that the added static private method has thrown an exception for the employee name:

The name “Sia” which we have passed in the Employee Constructor is not according to the “if” statement specified in the static #verify() method. That’s why the “employee” instance is not created.

Why you should use Private Methods in JavaScript

Here is a list of some of the advantages of using private methods in JavaScript:

  • Encapsulation is one of the key advantages of using private methods as it permits interfaces to hide the implementation details from other classes.
  • It also improves the readability of the code.
  • Defining private methods also ensures code re-usability and avoids code duplication.
  • If you declare all of your methods as “public”, you have to keep a check on who is going to read and make changes to the class properties.

Conclusion

Private methods are defined in JavaScript to hide crucial class methods or keep sensitive information private. In a class, to define a private method instance, private static method, or a private getter and setter, you have to prefix its name with the hash character #. This write-up explained the procedure to define the private methods in JavaScript with the help of suitable examples.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.