How to create Private Properties in JavaScript.

We don’t have Access Modifiers in JavaScript, and all properties of an object are public, which means you can read and modify them outside the object.

But what if you have a requirement to create private properties?  Consider Product object as mentioned below,


let Product = {

  id: '1',
  price: 200,
  title: 'Pencil'
}
console.log(Product.id); 

By default, JavaScript allows you to read and modify all the properties. But by using the Proxy objects, you can create private properties in an object.  

The Proxy object,

  • is a virtualizing interface to control the behavior of the object
  • provides custom behavior for the basic operations such as read and write on the object properties

As you see, the Proxy object created for the Product object can throw an error on the reading of a particular property. So, let us see how we can use the Proxy object to make ‘id’ as the private property of the Product object.

A Proxy object can be created using the Proxy constructor that takes two parameters,

  1. Target object – The  proxy virtualizes it and adds custom behaviors
  2. Handler – It is an object that contains the custom behavior. This can have set and get methods.

So, you can write Proxy for Product object to make ‘id’ as private property as shown below,


var productProxy = new Proxy(Product, {
  get: (obj, prop) => {
    if (prop == 'id') {
      return new Error(prop + ' - is private');
    }
    return obj[prop];
  },
  set: (obj, prop, value) => {

    if (prop == 'id') {
      throw new Error(prop + ' - is private');
    }
    obj[prop] = value;
    return true;
  }

})

That’s it. You just have to create another Proxy object and, in the setter, and getter check for the property name and throw an error.  Now when you try to read or write id property, JavaScript throws you an error.


productProxy.id = 9;  // error id - is private 
console.log(productProxy.id); // Error id - is private


I hope you like this quick lesson on making a JavaScript property private.  You can learn more about Proxy object in this video:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s