Hide object properties with JavaScript symbols
Written by Stefan Judis
- Published at
- Updated at
- Reading time
- 1min
This post is part of my Today I learned series in which I share all my web development learnings.
I've just read Exploring JavaScript Symbols, and it's quite good. It includes a tiny JavaScript nugget that I wasn't very aware of.
JS symbols are an underrated language feature that I probably should use for more things. And let alone the nicely nerdy well-known symbols that help you to really understand how JavaScript works under the hood.
One of these symbol use cases is hiding properties in a good old JavaScript objects.
const lastTouched = Symbol('lastTouched');
const record = {
name: 'schnitzel'
// use a symbol as a property key to hide the
// property from "standard" object operations
[lastTouched]: 'right now',
};
// access the `lastTouched`
console.log(record); // Object { name: "schnitzel", Symbol("lastTouched"): "right now" }
console.log(record[lastTouched]); // 'right now'
// don't worry about the property leaking somewhere
Object.keys(record); // Array [ 'name' ]
Object.entries(record); // Array [ Array [ "name", "schnitzel" ] ]
Object.values(record); // Array [ Array [ "schnitzel" ] ]
JSON.stringify(record); // '{ "name": "schnitzel" }'
for (let key in record) { console.log(key); } // "name"
A symbol property won't appear in Object
and friends, will be ignored in JSON
and is safely hidden in for-in
loops. Pretty nice!
If you enjoyed this article...
Join 5.4k readers and learn something new every week with Web Weekly.
Reply to this post and share your thoughts via good old email.