DEV Community

Cover image for Private object
zuzexx
zuzexx

Posted on • Edited on

Private object

In the world of web development, it is crucial to ensure the security of sensitive information such as usernames and passwords. To achieve this, there are various methods available to developers, such as hashing, salting, and encryption. In this post, we will focus on a different approach: using symbols in JavaScript to secure the properties of a user object.

What is a symbol?

A symbol is a unique and immutable data type in JavaScript that can be used as a property key. Unlike strings, symbols are not enumerable and therefore cannot be accessed using a for...in loop or the Object.keys() method. This makes symbols a useful tool for hiding the properties of an object, as they cannot be accessed directly.

More on Symbols

Here is an example of how you can use symbols to secure the username and password properties of a user object:

Example

/**
Create a user object that has properties 
username, password and age.
ensure that password and username are secure.
They cannot be called with user.username or user.password
 */
Enter fullscreen mode Exit fullscreen mode

Solution code & explanation

const username = Symbol("username");
const password = Symbol("password");

const firstUser = {
  [username]: "Bianca",
  [password]: "password123",
  age: 21,
};

Enter fullscreen mode Exit fullscreen mode

In this code, we create two symbols using the Symbol() constructor, username and password. These symbols are then used as property keys when defining the first user object, which has the properties username, password, and age. The values of these properties are set to "Bianca", "password123", and 21, respectively.

If we want to console.log() username or password we get undefined instead of the value.

console.log(firstUser.username);
console.log(firstUser.password);
console.log(firstUser.age);

/*Result:
undefined
undefined
21

*/
Enter fullscreen mode Exit fullscreen mode

Conclusion

It is important to note that this method of securing properties is not foolproof. The properties can still be accessed if someone has access to the source code and knows the symbols used as property keys. However, it does provide an additional layer of security that can make it more difficult for attackers to access sensitive information.

In conclusion, symbols can be a useful tool for securing the properties of objects in JavaScript. By using symbols as property keys, we can hide properties from direct access and make it more difficult for attackers to access sensitive information.

Top comments (0)