Why and where need to use javascript Symbol primitive types. I don't understand this concept.I Feel I will mad

In javascript ES6 currenty I am watching a video based on Symbol primitive type. I have read the documentation of mdn but I didn’t understand what this is and where need to use it and also why?

const id = Symbol.for("new symbol");

const id2 = Symbol.for("keys");

const id3 = Symbol.for("keys");

const personInfo = {

  Name: "Prite Dey",

  like: "Pet",

};

personInfo[id] = 1;

console.log(personInfo);

Anyone please help me to understand this.

Hi @rkprite09 :wave:

I haven’t used Symbol myself yet, but from reading a few articles I think there are two main usages for Symbols:

  • Encapsulate/Hide inner state of objects by using Symbols as object keys. Symbols aren’t accessible by traditional methods like JSON.stringify() or for...in loops:
let hiddenState = Symbol('state');
let task = {
    [hiddenState]: "processing",
    title: "Symbols Exercise",
    description: 'Learning about Symbols'
};
console.log(JSON.stringify(task)); // "{'title':'Symbols Exercise','description':'Learning about Symbols'}"

for (let key in task) {
  console.log(task[key]); // "Symbols Exercise" "Learning about Symbols"
}

// new method "getOwnPropertySymbols"
const [state] = Object.getOwnPropertySymbols(task)
console.log(state); // Symbol("state")
console.log(task[state]); // processing
  • Using built-in Symbols to augment own classes like Symbol.iterator to make a class iterable:
class List {
    constructor() {
        this.elements = [];
    }

    add(element) {
        this.elements.push(element);
        return this;
    }

    *[Symbol.iterator]() {
        for (let element of this.elements) {
            yield  element;
        }
    }
}

let chars = new List();
chars.add('A')
     .add('B')
     .add('C');

// because of the Symbol.iterator
for (let c of chars) {
    console.log(c);
}

// A
// B
// C

Those examples were taken/modified from https://www.javascripttutorial.net/es6/symbol/
I also recommend http://thecodebarbarian.com/a-practical-guide-to-symbols-in-javascript.html

I hope that makes it a bit clearer. It’s a rather advanced topic, but quite interesting!
Michael