This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
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!
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis

Stefan Judis | Sciencx (2024-11-15T23:00:00+00:00) Hide object properties with JavaScript symbols (#tilPost). Retrieved from https://www.scien.cx/2024/11/15/hide-object-properties-with-javascript-symbols-tilpost/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.