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. It's a good read and includes an interesting JavaScript nugget.
JS symbols are such an underrated language feature and if you dive deeper into the nicely nerdy well-known symbols you'll better understand how JavaScript works under the hood. Thumbs up for symbols! ๐
One symbol use case 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. Nice!
If you enjoyed this article...
Join 6.1k readers and learn something new every week with Web Weekly.
Reply to this post and share your thoughts via good old email.