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?
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