DEV Community



mohananagavenkat profile image Mohana Naga Venkat Sayempu ・1 min read

Symbols are created with the Symbol function. Each newly created symbol value is guaranteed unique. The argument passed to Symbol() is the symbol's description. It is good practice to always give a symbol a description to aid with debugging.

var firstName = Symbol('firstName');
console.log(firstName); // 'Symbol(firstName)'

Pseudo Private Properties

Symbols can be used as computed property identifiers in objects and classes. The related value is therefore somewhat private to code that does not have a reference to the symbol itself, for example, code in other modules. The value is not strictly private however since the symbol and its value are still enumerable via reflection APIs.

const PRIVATE_VALUE = Symbol('privateValue');
const PRIVATE_METHOD = Symbol('privateMethod');

class Foo {

  constructor () {
    this.publicValue = 'bar';
    this[PRIVATE_VALUE] = 'baz';

    // Can't see or call me without jumping through hoops

Symbol Constants

Symbols can be a better choice than strings for the values of constants since they are guaranteed unique.

const COLOR_RED = Symbol('colorRed');
const COLOR_GREEN = Symbol('colorGreen');
const COLOR_BLUE = Symbol('colorBlue');

Happy Coding 😀

Discussion (0)

Forem Open with the Forem app