DEV Community

Cover image for JavaScript Object Privacy
Bello Osagie
Bello Osagie

Posted on • Edited on

JavaScript Object Privacy

host.png


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:

const bankAccount = {
    _accountNumber: 16234950
}
Enter fullscreen mode Exit fullscreen mode

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

bankAccount.accountNumber = 16224971;
bankAccount.accountNumber; // 16224971
Enter fullscreen mode Exit fullscreen mode

See another example below:

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
Enter fullscreen mode Exit fullscreen mode

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.

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 
Enter fullscreen mode Exit fullscreen mode

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

More on classes later.


image.png


Learn on Skillshare

Top comments (0)