# JavaScript Object Privacy

[![host.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1613285550606/kVnFkQSP1.png)](https://partners.hostgator.com/MaZ1N)

---
An object or properties sometimes shouldn't be altered, accessed, or updated. In such a situation, they should be private.

We can indicate an object or property name is private by prepending an underscore (`_`) to it.

See the example below:

```js
const bankAccount = {
    _accountNumber: 16234950
}
``` 

The issue of using `_` is that an object or property can still be mutable (changed).

```js
bankAccount.accountNumber = 16224971;
bankAccount.accountNumber; // 16224971
```

See another example below:

```js
const person = {
  name: 'Bello',

  set _setPerson(name) {
    if (typeof this.name === 'string') {
      this.name = name;
    } else { 
      "Give a valid name";
    }
  } 
};

person._setPerson = 'John';
console.log(person.name) // John
```

The `_` only waves a flag to other developers to not alter it.

JavaScript now has a solution, introduced in **ES12** (**ECMAScript 2021**).  

Instead of the underscore (`_`), the hash symbol can be used (`#`). `#` is used most of the time in classes.

```js
class Person {
  get name() {
    return "Bello"
  }
  set name(value) {}

  get #age() {
    return 27
  }
  set #age(value) {}
}

const obj = new Person();
console.log(obj.name, obj.age); // Bello undefined 
```

For the above example to work, you might need to update your browser.

More on classes later.

---

[![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1613216267892/cgCrviTiF.png)](https://www.buymeacoffee.com/techstackmedia)

---

<a href="https://skillshare.eqcm.net/c/2680282/300216/4650" target="_top" id="300216"><img src="//a.impactradius-go.com/display-ad/4650-300216" border="0" alt="Learn on Skillshare" width="300" height="250"/></a><img height="0" width="0" src="https://skillshare.eqcm.net/i/2680282/300216/4650" style="position:absolute;visibility:hidden;" border="0" />
