JS -Symbols and when to use?

Vinayak Hegde
2 min readDec 13, 2020

--

Symbols

Symbols are new primitive type introduced in ES6. Symbols are completely unique identifiers. Just like their primitive counterparts (Number, String, Boolean), they can be created using the factory function Symbol() which returns a Symbol. Symbols are incomplete as a constructor because it does not support the syntax new Symbol().

const symbol = Symbol('symbol_description');> symbol
Symbol(symbol_description)

When do you use Symbols?

Use symbols when your requirement is one of these:

  • Privacy: when you don’t want your object properties to be enumerable

Symbols are not enumerable in for...in iterations. In addition, Object.getOwnPropertyNames() will not return symbol object properties, however, you can use Object.getOwnPropertySymbols() to get these.

const myObject = {
[Symbol('my_key')]: 1,
a: 2,
b: 3
};
// Ignores symbol-valued property keys:
> Object.getOwnPropertyNames(myObject)
['a', 'b']
// Ignores string-valued property keys:
> Object.getOwnPropertySymbols(myObject)
[Symbol(my_key)]
// Considers all kinds of keys:
> Reflect.ownKeys(myObject)
[Symbol(my_key),'a', 'b']
// Only considers enumerable property keys that are strings:
> Object.keys(myObject)
['a', 'b']
  • Enum: To allow you to define constants with semantic names and unique values.
const USER = {
ADMIN: Symbol(‘ADMIN’),
DEVELOPER: Symbol(‘DEVELOPER’),
MANAGER: Symbol(‘MANAGER’),
TESTER: Symbol(‘TESTER’)
};

Conclusion

Symbols in JavaScript can provide access level uniqueness to objects. It's worthwhile for all developer to have a basic understanding of them and their various use-cases. Use it when you can, because Symbols are very powerful, its pity that many developers don’t use it in real application.

--

--

Vinayak Hegde
Vinayak Hegde

Written by Vinayak Hegde

Dad, Husband, Son, Brother, Coder (mostly JavaScript and python), micro-blogger

No responses yet