Javascript - Data Types Using Symbols

Introduction

Symbols are mainly used as unique property keys because a symbol can never clash with any other property.

Consider the following example, where we have an object Person with some "public" properties:

let Person = { 
    name: "John", 
    age: 14, 
    location: "New York" 
} 

Now let's suppose we want to add a private method to the Person object. We can do that using Symbols as follows:

Demo

let votingEligibility = Symbol(); 

let Person = { //  www  . j  a  va 2  s  .  c  o  m
    name: "John", 
    age: 14, 
    location: "New York" 
} 

Person[votingEligibility] = function() { 
         return this.age >= 18; 
} 
console.log(Person);

Result

You can see that an anonymous method has been added to it.

You can use computed property keys here:

let Person = { 
        name: "John", 
        age: 14, 
        location: "New York", 
        [Symbol()]: function() { 
                return this.age >= 18; 
        } 
} 

The Symbol property is non-enumerable and anonymous.

Therefore, when using the for...in loop, symbol properties of the object won't be accessible while traversing.

You can get the Symbol property using Object.getOwnPropertySymbols(). For example:

Object.getOwnPropertyNames(Person); 
// ["name", "age", "location"] 

Object.getOwnPropertySymbols(Person); 
// [Symbol()] 

Here is how you would use Object.getOwnPropertySymbols() in the previous example where we created the Person object.

let canVote = Object.getOwnPropertySymbols(Person)[0]; 
Person[canVote](); // false 

You can achieve this by using the reference created to bind the property with the Person object.

Person[votingEligibility](); // false 

Related Topic