A presentation at Node.js Meetup #34 in May 2019 in Berlin, Germany by Robin Pokorny
Symbols complicated it all by Robin Pokorny Node.js Meetup #34 @robinpokorny
Why talk about it?
Symbols const sym = Symbol(); typeof sym; // -> “symbol” sym === Symbol(); // -> false
Primitive values boolean number string undefined null symbol
Primitive values boolean number string undefined null symbol complication #1
What for? const sym = Symbol() const o = { name: “My key is a string” [sym]: “My key is a symbol” } o[sym1] // -> “My key is a symbol”
Convertion Boolean(sym); // -> true !sym; // -> false
Convertion Number(sym); // -> TypeError sym * 5; // -> TypeError complication #2
Convertion String(sym); // -> “Symbol()” “” + sym; ${sym}; // -> TypeError complication #3
; ${sym}
Object inspection
symbol vs enumerable
const c = Symbol(); const d = Symbol(“d”); const o = { a: 1, [c]: 10 }; // non-enumerable by default Object.defineProperty(o, “b”, { value: 2 }); Object.defineProperty(o, d, { value: 20 });
Access o.a; // -> o.b; // -> o[c]; // -> o[d]; // -> 1 2 10 20
hasOwnProperty o.hasOwnProperty(“a”); // -> true o.hasOwnProperty(“b”); // -> true o.hasOwnProperty(c); // -> true o.hasOwnProperty(d); // -> true
keys Object.keys(o); // -> [“a”] Object.entries(o); // -> [[“a”, 1]] complication #4
Descriptors Object.getOwnPropertyDescriptors(o); // -> { // a: {…}, b: {…}, // Symbol(): {…}, Symbol(d): {…} // } complication #5
getOwn Object.getOwnPropertyNames(o); // -> [“a”, “b”] Object.getOwnPropertySymbols(o); // -> [Symbol(), Symbol(d)]
assign Object.assign({}, o); // -> {a: 1, Symbol(): 10} { …o }; // -> {a: 1, Symbol(): 10}
JSON JSON.stringify(o); // -> {"a":1} complication #6
{"a":1}
Reflect Reflect.ownKeys(o); // -> [“a”, “b”, Symbol(), Symbol(d)]
Where to use
. Hidden properties onst ROLE = Symbol(); onst createAdmin = name => ({ name, [ROLE]: “admin” ); onst isAdmin = ({ [ROLE]: role }) => role === “admin”
Some well-known symbols @@iterator @@toPrimitive @@match @@isConcatSpreadable
Symbols are your friends! If you do not overuse them…
/robinpokorny symbols-complicated-it-all.netlify.com