DEV Community

Mitesh Kamat
Mitesh Kamat

Posted on

4

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!!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay