DEV Community

Mitesh Kamat
Mitesh Kamat

Posted on

Purpose of Symbol()

Introduction

This post is about how we can make use of Symbol() in javascript.

A “symbol” represents a unique identifier which can be created using Symbol():

let firstSymbol = Symbol();
typeof(firstSymbol)  //symbol

We can give description to a symbol like:

let dummy = Symbol("dummy");
console.log(dummy);   // Symbol(dummy)

What is the use??

Symbols allow us to create “hidden” properties of an object, that no other part of code can accidentally access or overwrite.

1) Using symbols as unique values
Whenever we use a string or a number in our code, we tend to use enums.We should use symbols instead.

let statuses = {
    PENDING: Symbol('Pending'),
    REQUESTED: Symbol('Requested'),
    IN_PROGRESS: Symbol('In progress'),
    COMPLETED: Symbol('Completed'),
    ERROR: Symbol('Error')
};
// complete a task
myObject.setStatus(statuses.COMPLETED);

2) Using symbol as the computed property name of an object

let status = Symbol('status');
let task = {
    [status]: statuses.REQUESTED,
    description: 'Request'
};
console.log(task);
//{description: "Request", Symbol(status): Symbol(Requested)}

As mentioned at the start, it is just a unique identifier. There could be other use cases where we can make use of symbol.

Hope it helps you.
Cheers!!

Top comments (0)