Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Private Properties | Classes
Advanced JavaScript Mastery
course content

Course Content

Advanced JavaScript Mastery

Advanced JavaScript Mastery

1. Classes
2. DOM Manipulation
3. Events and Event Handling
4. Asynchronous JavaScript and APIs

bookPrivate Properties

In class-based programming, there are often cases where you want to limit direct access to certain properties to protect data integrity and control how it's modified.

What Are Private Properties?

In JavaScript, class properties are typically public, meaning they can be accessed and modified from outside the class. However, there are situations where you need to restrict access to certain properties, ensuring they can only be accessed or modified within the class itself. These are called private properties.

Private properties help create a clear boundary between the internal workings of the class and external code. They are useful when you want to hide sensitive data or prevent unintended changes to a property from outside the class.

Think of it like the engine of a car. While you can drive the car and interact with its controls, you don't have direct access to its engine components while driving. The engine is protected from external tampering, and only authorized mechanics (class methods) can make adjustments.

How to Declare and Use Private Fields in a Class

In JavaScript, private properties are declared using the # syntax (introduced in ES2020). By prefixing a property name with #, you make it private, meaning it can only be accessed within the class itself.

12345678910111213141516171819202122
class Animal { #type; // Declaring a private field constructor(name, type) { this.name = name; this.#type = type; // Assigning a value to the private field } getInfo() { return `${this.name} is a ${this.#type} animal.`; } changeType(newType) { this.#type = newType; // Modifying the private field within the class } } const lion = new Animal('Lion', 'Wild'); console.log(lion.getInfo()); // Output: Lion is a Wild animal // Attempt to access private field directly (this will cause an error) console.log(lion.#type); // Uncaught SyntaxError: Private field '#type' must be declared in an enclosing class
copy

In this example, #type is a private field. It cannot be accessed or modified outside the Animal class. Any attempt to access #type directly from an instance (like lion.#type) will result in a syntax error. This ensures that sensitive or critical data is only modified through controlled methods defined in the class.

Benefits of Private Properties

  1. Private properties protect sensitive data by preventing external access. They ensure that data can only be modified through specific methods, reducing the risk of accidental or unauthorized changes;
  2. Private properties allow you to encapsulate implementation details, hiding internal logic from the user. This promotes clean separation of concerns and keeps your code modular;
  3. With private properties, you have finer control over how data is accessed and modified within a class, ensuring that modifications happen through well-defined methods.

Real World Example: Bank Account

Let's take a real-world analogy of managing a bank account balance. In a bank, the balance of your account is protected, and no one can access or change it directly. You can only interact with it through authorized processes like deposits and withdrawals. Similarly, we can use private properties in a class to protect the balance field from being accessed or modified directly.

12345678910111213141516171819202122232425262728293031323334353637
class BankAccount { #balance; // Private field constructor(owner, initialBalance) { this.owner = owner; this.#balance = initialBalance; } // Method to deposit money deposit(amount) { if (amount > 0) { this.#balance += amount; } } // Method to withdraw money withdraw(amount) { if (amount > 0 && amount <= this.#balance) { this.#balance -= amount; } } // Method to get account balance getBalance() { return `Account balance for ${this.owner}: $${this.#balance}`; } } const account = new BankAccount('John', 1000); account.deposit(500); console.log(account.getBalance()); // Output: Account balance for John: $1500 account.withdraw(200); console.log(account.getBalance()); // Output: Account balance for John: $1300 // Direct access to balance is not allowed console.log(account.#balance); // SyntaxError: Private field '#balance' must be declared in an enclosing class
copy

In this example, the #balance field is private and can only be accessed through public methods like deposit, withdraw, and getBalance. This ensures that the balance is modified in a controlled way, protecting it from unauthorized access or manipulation.

1. What is the main reason for using private properties in a class?
2. How do you declare a private property?
3. What will happen if you try to access a private property from outside a class?
What is the main reason for using private properties in a class?

What is the main reason for using private properties in a class?

Select the correct answer

How do you declare a private property?

How do you declare a private property?

Select the correct answer

What will happen if you try to access a private property from outside a class?

What will happen if you try to access a private property from outside a class?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 7
some-alt