#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 29 of 50medium

What is Symbol in JavaScript?

Understanding the Symbol primitive type.

What You'll Learn

  • What Symbols are
  • Creating and using Symbols
  • Well-known Symbols

What is Symbol?

Symbol is a primitive type for unique identifiers.

code.jsJavaScript
const sym1 = Symbol('description');
const sym2 = Symbol('description');

console.log(sym1 === sym2); // false (always unique)
console.log(typeof sym1);   // 'symbol'

Using Symbols as Keys

code.jsJavaScript
const id = Symbol('id');
const user = {
  name: 'John',
  [id]: 123
};

console.log(user[id]); // 123
console.log(Object.keys(user)); // ['name'] - Symbol not included

Global Symbol Registry

code.jsJavaScript
// Create/retrieve global symbol
const sym1 = Symbol.for('app.id');
const sym2 = Symbol.for('app.id');

console.log(sym1 === sym2); // true

// Get key from symbol
Symbol.keyFor(sym1); // 'app.id'

Well-Known Symbols

code.jsJavaScript
// Symbol.iterator
const iterable = {
  [Symbol.iterator]() {
    let i = 0;
    return {
      next() {
        return { value: i++, done: i > 3 };
      }
    };
  }
};

for (const n of iterable) {
  console.log(n); // 0, 1, 2
}

// Symbol.toStringTag
class MyClass {
  get [Symbol.toStringTag]() {
    return 'MyClass';
  }
}
console.log(Object.prototype.toString.call(new MyClass()));
// '[object MyClass]'