Understanding Private Properties in JavaScript

In the topic of object-oriented programming, the properties and methods can be divided into two categories, private and public.

The public properties are those that can be accessed from outside of the object. All of the examples we've seen so far are public properties.

Private properties cannot be accessed from the outside and can only be used by methods in the same class.

Most other programming languages offer a language-level way to define private properties, usually with the keyword private. But this feature has been missing in JavaScript for a long time.

Private properties

So JavaScript developers decided on a convention, that is, if a property name starts with an underscore (_), that property is considered private and should not be accessed from the outside.

javascript
1class User {
2  constructor(name) {
3    this._name = name; // This property is private
4    this.status = "Admin"; // This property is public
5  }
6}

Technically, this _name property can still be accessed.

javascript
1let user = new User("John Doe");
2
3console.log(user._name);
text
1John Doe

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉