Member-only story

Unveiling JavaScript’s Object Privacy: Public vs. Private Members

Learn how to control access to object properties and methods effectively

Max N
3 min readMar 22, 2024

In JavaScript, objects are used to encapsulate data and behavior. While all object properties and methods are technically public by default, there are ways to achieve privacy and control access to these members.

In this article, we’ll explore the concepts of public and private members in JavaScript and how to implement them effectively.

Public Members

Public members are properties and methods that are accessible from outside the object. They can be read, modified, or invoked by any part of the code that has a reference to the object. By default, all properties and methods defined within an object are public.

Here’s an example of an object with public members:

const person = {
name: 'Alice', // Public property
age: 25, // Public property
greet: function() { // Public method
console.log(`Hello, my name is ${this.name}`);
}
};

console.log(person.name); // Output: Alice
person.age = 26; // Modifying a public property
person.greet(); // Output: Hello, my name is Alice

In this example, name, age, and greet are all public members that can be…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet