JavaScriptFundamental (ES6), part 2
Symbol keys are hidden, not private, in JavaScript
68 A symbol key is hidden, not private
fairPut a symbol-keyed field on an order and check every way of listing properties: Object.keys, for...in, JSON.stringify, getOwnPropertySymbols, Reflect.ownKeys, spread and Object.assign. Then show that two symbols with the same description are different keys, and find the conversion that throws.
Stuck? Three hints, smallest first
- 1. The string-key APIs skip symbols entirely. There is a separate call for them.
- 2. Spread and
Object.assigncopy own enumerable properties — and a symbol key can be enumerable. - 3.
String(sym)is fine.'' + symis not.
const AUDIT = Symbol('audit');
const order = { customer: 'Bisi', total: 45000, [AUDIT]: 'Balogun till 3, 15:40' };
const stringKeys = Object.keys(order);
const enumerated = [];
for (const key in order) enumerated.push(key);
const serialised = JSON.stringify(order);
const revived = JSON.parse(serialised);
const symbolKeys = Object.getOwnPropertySymbols(order).map(String);
const everyKey = Reflect.ownKeys(order).map(String);
const readsFine = order[AUDIT];
const spread = { ...order };
const assigned = Object.assign({}, order);
const copiedTheSymbol = [spread[AUDIT], assigned[AUDIT], Object.keys(spread)];
const survivesRoundTrip = revived[AUDIT] === undefined;
const LOOKALIKE = Symbol('audit');
order[LOOKALIKE] = 'Ikeja till 1, 09:05';
const bothCoexist = [order[AUDIT], order[LOOKALIKE], Object.getOwnPropertySymbols(order).length];
const freshMisses = order[Symbol('audit')] === undefined;
const description = [AUDIT.description, String(AUDIT), AUDIT === LOOKALIKE];
let conversion;
try { conversion = '' + AUDIT; } catch (err) { conversion = err.name; }
let templated;
try { templated = `${AUDIT}`; } catch (err) { templated = err.name; }
console.log('string keys :', stringKeys, '| serialised:', serialised);
console.log('symbol keys :', symbolKeys, '| every key:', everyKey);
console.log('conversions :', conversion, templated, String(AUDIT));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('Object.keys and for...in skip the symbol completely', [stringKeys, enumerated], [['customer', 'total'], ['customer', 'total']]);
test('JSON.stringify drops it, so it does not survive a round trip', [serialised, survivesRoundTrip], ['{"customer":"Bisi","total":45000}', true]);
test('getOwnPropertySymbols finds it and Reflect.ownKeys lists both kinds', [symbolKeys, everyKey], [['Symbol(audit)'], ['customer', 'total', 'Symbol(audit)']]);
test('and reading it by the symbol is ordinary property access', readsFine, 'Balogun till 3, 15:40');
test('spread and Object.assign do copy it: hidden is not private', copiedTheSymbol, ['Balogun till 3, 15:40', 'Balogun till 3, 15:40', ['customer', 'total']]);
test('two symbols with the same description are different keys, so both values live', bothCoexist, ['Balogun till 3, 15:40', 'Ikeja till 1, 09:05', 2]);
test('a fresh symbol with that description reads nothing: the value is the identity', freshMisses, true);
test('the description is readable, and String() converts safely', description, ['audit', 'Symbol(audit)', false]);
test('but implicit conversion throws, in both + and a template literal', [conversion, templated], ['TypeError', 'TypeError']);
Symbol keys are for metadata you do not want in the way: an audit trail, a cache slot, a framework's bookkeeping. They are skipped by Object.keys, for...in, JSON.stringify and getOwnPropertyNames, so none of the loops in existing code trips over them and no serialiser leaks them.
They are not private, and the fifth assertion is the one to remember. Spread and Object.assign copy own enumerable properties, and enumerable has nothing to do with being a string, so the symbol comes along — while Object.keys of the copy still shows two keys. Anyone can also list them with getOwnPropertySymbols. For real privacy you need a #field or a WeakMap, as exercise 63 shows.
The identity point is the sixth and seventh assertions together. A symbol's description is a label for debugging, nothing more: two symbols described as 'audit' are two distinct keys and both values sit on the object at once. That is the feature — it is why a library can add Symbol('cache') to your object with no chance of colliding with yours — and it is why you must keep the symbol itself around, because there is no way to look one up by description. Exercise 69 is the deliberate exception.
The last assertion is the sharp edge. A symbol refuses implicit string conversion and throws a TypeError, so 'key: ' + sym and `${sym}` both fail. It is deliberate — silently turning a unique key into the text "Symbol(audit)" would defeat the point — but it means every log line and every error message that might touch a key needs String(k), which is why the traps in exercise 60 are written that way.