Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
data type

What are JavaScript symbols?

Educative Answers Team

A symbol is a new, primitive, data type that was introduced in JavaScript ES6; it is a special, unique, value.


Some basics

A symbol is declared using a factory function, it takes in an optional descriptor. This descriptor has no effect on the symbol but it is beneficial for debugging purposes.

// Symbols are unique
let sym1 = Symbol();
let sym2 = Symbol();
console.log(sym1 === sym2);
// The descriptor has no effect on the uniqueness of the symbol.
let sym3 = Symbol('jelly');
let sym4 = Symbol('jelly');
console.log(sym3 === sym4);

Usually, symbols with the same descriptor are different. However, there are cases when it is desirable for symbols with the same descriptors to be the same entities.

Here is where the global symbol registry comes into the picture. When symbols are created here, at the global symbol registry, it is guaranteed that all subsequent accesses made, using the same descriptor, will access the same entity.

Symbols created in the global system registry are created differently than those that are not.

let sym1 = Symbol.for('jelly');
let sym2 = Symbol.for('jelly');
console.log(sym1 === sym2);

Important use cases

1. Symbols as object keys

Suppose that there are two libraries, A and B, developed by two different teams. Both teams need to add a property to work on an object but, they both end up naming their property id by coincidence. This coincidence leads to one of the libraries overwriting the value stored in id.

Before ES6, when the object key could only be of the string type, this scenario was a real possibility. String type object keys posed the danger of name collision and led to the overwriting of values.

Symbols have provided an elegant solution to this problem.

let student = { name: "Lilly" };
// Instead of doing user.id = "ID";, 
// the libraries can do the following
let id_libA = Symbol("id");
student[id_libA] = "ID assigned by library A";
let id_libB = Symbol("id");
student[id_libB] = "ID assigned by library B";
console.log(student)

2. Hiding symbolic properties while using a for in loop

Symbolic properties do not show when iterating an object using a for in loop; this thereby simulates private properties.

let id = Symbol()
let student = { name: "Lilly" , cgpa: "3.8", [id]: "123"};
for (let keys in student){
    console.log(keys);
}

RELATED TAGS

javascript
data type
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring