How to Use Symbols as Object Keys in JavaScript?

Estimated read time 2 min read

In JavaScript, symbols can be used as object keys to define properties with unique names. This can be useful when you want to define hidden properties that should not be accessed by other code. Here’s how you can use symbols as object keys in JavaScript:

  1. Create a symbol: To create a symbol, you can use the Symbol() function. You can also provide a description for the symbol as an argument, but this is optional.
const mySymbol = Symbol();
const myDescribedSymbol = Symbol('My Described Symbol');
  1. Use symbols as object keys: You can use symbols as object keys by defining an object property using the square bracket notation and including the symbol as the key.
const myObject = {
  [mySymbol]: 'My Symbol Key'
};
console.log(myObject[mySymbol]); // Output: My Symbol Key
  1. Accessing symbol properties: To access a symbol property, you can use the square bracket notation and include the symbol as the key.
console.log(myObject[mySymbol]); // Output: My Symbol Key
  1. Enumerating symbol properties: Note that symbol properties are not enumerable by default, so they won’t show up in a for…in loop or Object.keys() call. To enumerate symbol properties, you can use the Object.getOwnPropertySymbols() method.
const symbolProperties = Object.getOwnPropertySymbols(myObject);
console.log(symbolProperties); // Output: [Symbol()]

By using symbols as object keys, you can define hidden properties that cannot be accidentally overridden or accessed by other code. This can help make your code more robust and maintainable.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply