JavaScript Symbols: A Guide

JavaScript Symbols: A Guide

In JavaScript, like other programming languages, there are many data types. Symbol is a primitive data type in JavaScript like string and numbers.Symbol is immutable and is guaranteed to be unique. Symbol is introduced in ES6. For example:

// Two symbols with the same description
const val1 = Symbol('hello');
const val2 = Symbol('hello');

console.log(val1 === val2); // false

Although val1 and val2 both contain the same description, they are different.

Creating Symbol

Symbol() function is used to create a Symbol. for instance:

// creating symbol
const y = Symbol()

typeof y; // symbol

An optional string can be passed as the description for a symbol. for example:

const y = Symbol('hey');
console.log(y); // Symbol(hey)

Access Symbol Description

You can access the description of a symbol by using the . operator.

const y = Symbol('foo');
console.log(y.description); // foo

"Hidden" Properties of Objects

Symbols can be used to create hidden properties for an object. This means that no other part of the code can accidentally access or overwrite them.

Add Symbol as an Object Key

You can add symbols as a key in an object using square brackets []. For example,

let id = Symbol("id");

let person = {
    name: "Lisa",
    // adding symbol as a key
    [id]: 5842 // not "id": 123
};

console.log(person); // {name: "Lisa", Symbol(id): 5842}

Symbols are skipped by for..in loop

The for...in loop does not iterate over the Symbolic properties of an object.

let id = Symbol("id");

let person = {
    name: "John",
    age: 34,
    [id]: 7895
};

// using for...in
for (let key in person) {
    console.log(key);
}

// name 
// age

Symbols and JSON.stringify()

Symbol-keyed properties will be completely ignored when using JSON.stringify():

JSON.stringify({ name: "John", [Symbol("id")]: 123 });
// '{ "name": "John"}'

Finding Symbol properties on objects

You can use Object.getOwnPropertySymbols() method to find Symbol properties of a given object. Be aware that Object.getOwnPropertyNames() will not return the Symbol properties of an object.

Symbol Methods

There are various methods available with Symbol. for and keyFor() are two of the most used.

Symbol.for(key)

Symbol.for(key) returns a symbol by name. If nothing found, a new Symbol will be created with key.

Symbol.keyFor(sym)

Symbol.keyFor(sym) return a key for the given Symbol.

// get symbol by name
let sym = Symbol.for('name');
let sym1 = Symbol.for('ssn');

// get name by symbol
console.log( Symbol.keyFor(sym) ); // name
console.log( Symbol.keyFor(sym1) ); // ssn

Symbol.toString()

The toString() method returns a string representing the specified symbol value.

Symbol.for("asc").toString(); // "asc"

Summary

Symbols are often used to create unique object properties that do not collide with other object properties in the code. This provides a form of weak encapsulation or information hiding.