Symbols complicated it all

A presentation at Node.js Meetup #34 in May 2019 in Berlin, Germany by Robin Pokorny

Slide 1

Slide 1

Symbols complicated it all by Robin Pokorny Node.js Meetup #34 @robinpokorny

Slide 2

Slide 2

Why talk about it?

Slide 3

Slide 3

Symbols const sym = Symbol(); typeof sym; // -> “symbol” sym === Symbol(); // -> false

Slide 4

Slide 4

Primitive values boolean number string undefined null symbol

Slide 5

Slide 5

Primitive values boolean number string undefined null symbol complication #1

Slide 6

Slide 6

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”

Slide 7

Slide 7

Convertion Boolean(sym); // -> true !sym; // -> false

Slide 8

Slide 8

Convertion Number(sym); // -> TypeError sym * 5; // -> TypeError complication #2

Slide 9

Slide 9

Convertion String(sym); // -> “Symbol()” “” + sym; ${sym}; // -> TypeError complication #3

Slide 10

Slide 10

Object inspection

Slide 11

Slide 11

symbol vs enumerable

Slide 12

Slide 12

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 });

Slide 13

Slide 13

Slide 14

Slide 14

Access o.a; // -> o.b; // -> o[c]; // -> o[d]; // -> 1 2 10 20

Slide 15

Slide 15

hasOwnProperty o.hasOwnProperty(“a”); // -> true o.hasOwnProperty(“b”); // -> true o.hasOwnProperty(c); // -> true o.hasOwnProperty(d); // -> true

Slide 16

Slide 16

keys Object.keys(o); // -> [“a”] Object.entries(o); // -> [[“a”, 1]] complication #4

Slide 17

Slide 17

Descriptors Object.getOwnPropertyDescriptors(o); // -> { // a: {…}, b: {…}, // Symbol(): {…}, Symbol(d): {…} // } complication #5

Slide 18

Slide 18

getOwn Object.getOwnPropertyNames(o); // -> [“a”, “b”] Object.getOwnPropertySymbols(o); // -> [Symbol(), Symbol(d)]

Slide 19

Slide 19

assign Object.assign({}, o); // -> {a: 1, Symbol(): 10} { …o }; // -> {a: 1, Symbol(): 10}

Slide 20

Slide 20

JSON JSON.stringify(o); // -> {"a":1} complication #6

Slide 21

Slide 21

Reflect Reflect.ownKeys(o); // -> [“a”, “b”, Symbol(), Symbol(d)]

Slide 22

Slide 22

Where to use

Slide 23

Slide 23

. Hidden properties onst ROLE = Symbol(); onst createAdmin = name => ({ name, [ROLE]: “admin” ); onst isAdmin = ({ [ROLE]: role }) => role === “admin”

Slide 24

Slide 24

  1. Meta-data Well-known symbols on Symbol object Symbol.iterator written as @@iterator Option for libraries

Slide 25

Slide 25

Some well-known symbols @@iterator @@toPrimitive @@match @@isConcatSpreadable

Slide 26

Slide 26

Symbols are your friends! If you do not overuse them…

Slide 27

Slide 27

/robinpokorny symbols-complicated-it-all.netlify.com