Hi @rkprite09
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