Published at
Updated at
Reading time
1min

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.keys and friends, will be ignored in JSON.stringify and is safely hidden in for-in loops. Nice!

If you enjoyed this article...

Join 6.3k readers and learn something new every week with Web Weekly.

Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles