Understanding Public and Private Fields in JavaScript Class

Understanding Public and Private Fields in JavaScript Class

Somethings should always be left private. That’s nothing said of when using classes in JS. But in recent times, proposals have come up to add some privacy to the JS class. We will explore that in this post.

Somethings should always be left private. That’s nothing said of when using classes in JS. But in recent times, proposals have come up to add some privacy to the JS class. We will explore that in this post.

Adding some privacy to the JS class? Let’s explore that in this post…

Privacy

In other languages like Java C++, they have access to modifiers like private, public and protected. All these control access to a class's variables and methods.

The primary purpose of public methods is to present to the class’s clients a view of the services the class provides (the class’s public interface). Clients of the class need not be concerned with how the class accomplishes its tasks. For this reason, the private variables and private methods of a class (i.e., the class’s implementation details) are not directly accessible to the class’s clients. — *[Java, How to program](http://www.deitel.com/Books/Java/JavaHowtoProgram10eEarlyObjects/tabid/3656/Default.aspx "Java, How to program*") Let’s say we have a class like this in Java:

class Time {
    private int secound;
    private int minutes;
    private int hour;
    Time(int hour, int secound, int minutes) {
        this.hour = hour;
        this.secound = secound;
        this.minutes = minutes;
    }
    public String buildString()
    {
        return String.format( "%24s: %s\n%24s: %s", "this.toUniversalString()", , "toUniversalString()", );
    } // end method buildString
    // convert to String in universal-time format (HH:MM:SS)
    public String toUniversalString()
    {
        return String.format( "%02d:%02d:%02d", , , );
    }
}

You see above we have a Time class that we can use to display the current time. It has three variables: hour, minutes, second each hold the current value of second, minute, and hour. Naturally, we can't allow users to modify the hour, minute and second variables. So that's the reason we made it private, trying to directly modify the variables outside the scope of the class will throw an error.

Time time = new Time(10, 12, 23);
time.hour = 2
TimeTest.java:9: hour has private access in Time
    time.hour = 2; // error: hour has private access in Time
        ^

You see, variables with the private access modifier can only be modified from inside the class not outside the class as we did above.

class Time {
    private int secound;
    private int minutes;
    private int hour;
    Time(int hour, int secound, int minutes) {
        this.hour = hour;
        this.secound = secound;
        this.minutes = minutes;
    }
    // ...
    public setHourToZero() {
        this.hour = 0
    }
}

You see we changed the private variable hour inside the class, inside the setHourZero method. Even methods are applicable also if we set a method to private it can only be called from inside the class, not outside the class.

class Time {
    private int secound;
    private int minutes;
    private int hour;
    Time(int hour, int secound, int minutes) {
        this.hour = hour;
        this.secound = secound;
        this.minutes = minutes;
    }
    private formatTime() {
        // ...
    }
    public trySomethingNew() {
        this.formatTime()
    }
    //...
}
Time time = new Time(10, 1, 2);
time. trySomeThingNew()
time.formatTime()
TimeTest.java:9: formatTime has private access in Time
    time.formatTime(); // error: method formatTime has private access in Time
        ^

We see that Java has privacy which enables to know delicate methods and variables we want to expose to or hide from the outside world.

Coming to JS, we can have the Time class like this:

class Time {
    constructor(hour, minute, second) {
        this.hour = hour
        this.minute = minute
        this.second = second
    }
    buildString() {
        return String.format( "%24s: %s\n%24s: %s", "this.toUniversalString()", , "toUniversalString()", );
    } // end method buildString
    // convert to String in universal-time format (HH:MM:SS)
    toUniversalString() {
        return String.format( "%02d:%02d:%02d", , , );
    }
}

JS have no privacy, there is no private or public access modifier. We can modify the variables at will.

const time = new Time(10, 2, 4)
time.hour = 20
time.minute = 10

You see we can play or mess around the variables at will.

The Proposal — Stage 3

Now there is a proposal to add private and public fields in classes. So we can add access modifiers to control the privacy of our variables in classes.

Private class field

With this new proposal, we can define private variables in our class using the hash # symbol.

class Time {
    #hour = 0
    #minute = 0
    #second = 0
    constructor(hour, minute, second) {
        this.#hour = hour
        this.#minute = minute
        this.#second = second
    }
    //...
}

Now, trying to modify either hour, minute or hour variables will throw an error.

const time = new Time(10, 2, 4)
time.#hour = 20 // will throw error #hour has a private access in Time
time.#minute = 10 // will throw error #minute has a private access in Time

So we see to add private access to fields we prefix the variable with the hash symbol, #.

Also, we can privatize our methods so it can only be accessible from within our class.

class Time {
    #hour = 0
    #minute = 0
    #second = 0
    constructor(hour, minute, second) {
        this.#hour = hour
        this.#minute = minute
        this.#second = second
    }
    #setZeroHour(int hour) {
        this.#hour = hour
    }
    callSetZeroHour() {
        this.#setZeroHour()
    }
    //...
}

We see that to privatise a method we also append the hash symbol # before it. We have a setZeroHour method above that we want only to be called inside the class, we appended # to it. If we try accessing the class it will throw an error.

const time = new Time(10, 2, 4)
time.#setZeroHour(0) // will throw error #setZeroHour has a private access in Time

Now, callSetZeroHour has no # appended to it so it is a public filed it can be accessed from outside the time class.

const time = new Time(10, 2, 4)
time.callSetZeroHour()

Private static properties

We can also privatize static properties in our class.

class Time {
    #hour = 0
    #minute = 0
    #second = 0
    static #gmt = 0
    constructor(hour, minute, second) {
        this.#hour = hour
        this.#minute = minute
        this.#second = second
    }
    //...
}

We added a static property gmt, which is only accessed by the class name, not from the instance of the Time class. Now the static property gmt is a private static property.

const time = new Time(10, 2, 4);
Time.#gmt // it will throw, static property #gmt is inaccessible from outside the Time class.

Trying to access it from outside the Time class will throw an error, to bypass this we have to access it from within the Time class.

class Time {
    #hour = 0
    #minute = 0
    #second = 0
    static #gmt = 0
    constructor(hour, minute, second) {
        this.#hour = hour
        this.#minute = minute
        this.#second = second
    }
    setGMT(int gmt) {
        Time.#gmt = gmt
    }
    //...
}
const time = new Time(10, 2, 4)
time.setGMT(9)

Now, this is the same as static methods:

class Time {
    #hour = 0
    #minute = 0
    #second = 0
    static #gmt = 0
    constructor(hour, minute, second) {
        this.#hour = hour
        this.#minute = minute
        this.#second = second
    }
    static displayHour() {
        return Time.#getHour()
    }
    static #getHour() {
        return this.#hour
    }
    //...
}

We have two static methods displayHour and #getHour. displayHour is accessible from outside the Time class and #getHour is only accessible from inside the Time class.

const time = new Time(10, 2, 4)
Time.#getHour() // Access denial error
Time.displayHour()

Conclusion

Isn’t this proposal awesome, imagine being able to privatise our variables in our class in JS. We will finally be able to code classes as we do in Java, C/C++. I can’t wait to use these in Chrome and Node.js.

javascript web-development

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Best Web and App Development Company in Ahmedabad

Contact DataPierce for any questions or queries you have about website development, designing, marketing projects or any small or enterprise software development.

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

For World Class Web Development Services in India visit RB Genie

Do you want excellent and world class web development services for your valuable projects? Contact **RB Genie **now, we have more than 8 years experienced team of web developers, which specializes in overall web design and website development...

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?